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

Unit 3

The document discusses various looping statements in Visual Basic such as Do Loops, For-Next Loops, While-Wend Loops, and nested loops. It provides the syntax for each loop and examples of how to use them. It also covers exiting loops early using Exit statements and assigning return values when exiting functions or properties.

Uploaded by

Aravindhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Unit 3

The document discusses various looping statements in Visual Basic such as Do Loops, For-Next Loops, While-Wend Loops, and nested loops. It provides the syntax for each loop and examples of how to use them. It also covers exiting loops early using Exit statements and assigning return values when exiting functions or properties.

Uploaded by

Aravindhan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 34

Subject : Visual Basic Programming

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:

• Do……Loop : The Do……Loop executes a block of statements for as


long as a condition is True.
• Visual Basic evaluates an expression, and if it’s True, the statements are
executed.
• If the expression is False, the program continues and the statement
following the loop is executed.
• There are two variations of the Do……Loop statement.

• 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

• To execute a block of statements until the condition becomes True, use


the following syntax :
• Do Until condition
• statement block

• Loop

• Another variation of the Do loop executes the statements first and


evaluates the condition after each execution. This Do…Loop has the
following syntax :
Do
• statements

• Loop While condition

• Or

• Do

• statements

• Loop Until condition

• For…..Next : The For…….Next loop is one of the oldest loop structures


in programming languages. Unlike the Do….loop, the For …..Next loop
requires that you know how many times the statements in the loop will be
executed.
• The For…Next loop uses a variable(it’s called the loop’s counter) that
increases or decreases in value during each repetition of the loop.
• 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 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.

• The general form is : If condition Then statement

• If……Then……Else : A variation of the If……Then statement is the


If……Then……Else statement, which executes one block of statements
if the condition is True and another if the condition is False. The syntax
of the If… Then….Else statement is as follows:
• If condition Then

• 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

The above example can be rewritten as


Do
counter=counter+1
Loop until counter>1000
Exiting the Loop
Sometime we need exit to exit a loop earlier when a certain condition is
fulfilled. The keyword to use is Exit Do. You can examine Example 9.2 for its
usage.

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:

For counter=startNumber to endNumber (Step increment)

One or more VB statements

Next
Example

Private Sub Command1_Click()


Dim counter As Integer
For counter = 1 To 10
List1.AddItem counter
Next
End Sub

Example
Private Sub Command1_Click()

Dim counter As Integer


For counter = 1 To 1000 Step 10
counter = counter + 1
Print counter
Next
End Sub
Example
For counter=1000 to 5 step -5
counter=counter-10
If counter<50 then
Exit For
Else
Print "Keep Counting"
End If
Next

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.

Nested For...Next Loop


When you have a loop within a loop, then you have created a nested loop.
You can actually have as many loops as you want in a nested loop provided the
loops are not the never-ending type. For a nested loop that consists of two loops,
the first cycle of the outer loop will be processed first, then it will process the
whole repetitive process of the inner loop, then the second cycle of the outer
loop will be processed and again the whole repetitive process of the inner loop
will be processed. The program will end when the whole cycle of the outer loop
is processed.
The Structure of a nested loop is :

For counter1=startNumber to endNumber (Step increment)


For counter2=startNumber to endNumber (Step increment)
One or more VB statements
Next counter2
Next counter1

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 While….Wend Loop


The structure of a While….Wend Loop is very similar to the Do Loop. it takes
the following form:
While condition
Statements
Wend

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

Exits a procedure or block and transfers control immediately to the statement


following the procedure call or the block definition.

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.

In a Set procedure, the Exit Property statement is equivalent to 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.

In a Sub procedure, the Exit Sub statement is equivalent to the Return


statement.

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.

Nested Control Structures:-

Control Statements are used to control the flow of program's execution.


Visual Basic supports control structures such as if... Then, if...Then ...Else,
Select...Case, and Loop structures such as Do While...Loop, While...Wend,
For...Next etc method.
If...Then selection structure

The If...Then selection structure performs an indicated action only when the
condition is True; otherwise the action is skipped.

Syntax of the If...Then selection

If <condition> Then
statement
End If

e.g.: If average>75 Then


txtGrade.Text = "A"
End If
If...Then...Else selection structure

The If...Then...Else selection structure allows the programmer to specify that a


different action is to be performed when the condition is True than when the
condition is False.

Syntax of the If...Then...Else selection

If <condition > Then


statements
Else
statements
End If

e.g.: If average>50 Then


txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If

Nested If...Then...Else selection structure

Nested If...Then...Else selection structures test for multiple cases by


placing If...Then...Else selection structures inside If...Then...Else structures.

Syntax of the Nested If...Then...Else selection structure

You can use Nested If either of the methods as shown above

Method 1

If < condition 1 > Then


statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If

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

If average > 75 Then


txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If

Select...Case selection structure

Select...Case structure is an alternative to If...Then...ElseIf for selectively


executing a single block of statements from among multiple block of
statements. Select...case is more convenient to use than the If...Else...End
If. The following program block illustrate the working of Select...Case.

Syntax of the Select...Case selection structure

Select Case Index


Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the
text box

Dim average as Integer

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

Arrays : Declaring and using arrays:-


An array is a set of values, which are termed elements, that are logically
related to each other. For example, an array may consist of the number of
students in each grade in a grammar school; each element of the array is the
number of students in a single grade. Similarly, an array may consist of a
student's grades for a class; each element of the array is a single grade.

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.

Handling large numbers of grades quickly becomes unwieldy. This in turn


makes an application much more likely to have serious bugs.

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.

Some quick examples before explanation:

VB

' Declare a single-dimension array of 5 numbers.


Dim numbers(4) As Integer

' Declare a single-dimension array and set its 4 values.


Dim numbers = New Integer() {1, 2, 4, 8}

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

' Declare a 6 x 6 multidimensional array.


Dim matrix(5, 5) As Double

' Declare a 4 x 3 multidimensional array and set array element values.


Dim matrix = New Integer(3, 2) {{1, 2, 3}, {2, 3, 4}, {3, 4, 5}, {4, 5, 6}}

' Declare a jagged array


Dim sales()() As Double = New Double(11)() {}
Array elements in a simple array
Let's create an array named students to store the number of students in each
grade in a grammar school. The indexes of the elements range from 0 through 6.
Using this array is simpler than declaring seven variables.

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

' Assign values to each element.


students(0) = 23
students(1) = 19
students(2) = 21
students(3) = 17
students(4) = 19
students(5) = 20
students(6) = 22

' Display the value of each element.


For ctr As Integer = 0 To 6
Dim grade As String = If(ctr = 0, "kindergarten", $"grade {ctr}")
Console.WriteLine($"Students in {grade}: {students(ctr)}")
Next
End Sub
End Module
' The example displays the following output:
' Students in kindergarten: 23
' Students in grade 1: 19
' Students in grade 2: 21
' Students in grade 3: 17
' Students in grade 4: 19
' Students in grade 5: 20
' Students in grade 6: 22

The example does three things:


It declares a students array with seven elements. The number 6 in the array
declaration indicates the last index in the array; it is one less than the number of
elements in the array.
It assigns values to each element in the array. Array elements are accessed by
using the array name and including the index of the individual element in
parentheses.
It lists each value of the array. The example uses a For statement to access each
element of the array by its index number.
The students array in the preceding example is a one-dimensional array because
it uses one index. An array that uses more than one index or subscript is called
multidimensional. For more information, see the rest of this article and Array
Dimensions in Visual Basic.

Creating an array
You can define the size of an array in several ways:

You can specify the size when the array is declared:

VB

' Declare an array with 10 elements.


Dim cargoWeights(9) As Double
' Declare a 24 x 2 array.
Dim hourlyTemperatures(23, 1) As Integer
' Declare a jagged array with 31 elements.
Dim januaryInquiries(30)() As String
You can use a New clause to supply the size of an array when it’s created:

VB

' Declare an array with 10 elements.


Dim cargoWeights() As Double = New Double(9) {}
' Declare a 24 x 2 array.
Dim hourlyTemperatures(,) As Integer = New Integer(23, 1) {}
' Declare a jagged array with 31 elements.
Dim januaryInquiries()() As String = New String(30)() {}
If you have an existing array, you can redefine its size by using the ReDim
statement. You can specify that the ReDim statement keep the values that are in
the array, or you can specify that it create an empty array. The following
example shows different uses of the ReDim statement to modify the size of an
existing array.

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.

Storing values in an array


You can access each location in an array by using an index of type Integer. You
can store and retrieve values in an array by referencing each array location by
using its index enclosed in parentheses. Indexes for multidimensional arrays are
separated by commas (,). You need one index for each array dimension.

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

' Write values to it.


For ctr As Integer = 0 To 9
numbers(ctr) = value
value *= 2
Next

' Read and sum the array values.


Dim sum As Integer
For ctr As Integer = 0 To 9
sum += numbers(ctr)
Next
Console.WriteLine($"The sum of the values is {sum:N0}")
End Sub
End Module
' The example displays the following output:
' The sum of the values is 2,046
Populating an array with array literals
By using an array literal, you can populate an array with an initial set of values
at the same time that you create it. An array literal consists of a list of comma-
separated values that are enclosed in braces ({}).

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

' Array literals with explicit type definition.


Dim numbers = New Integer() {1, 2, 4, 8}
' Array literals with type inference.
Dim doubles = {1.5, 2, 9.9, 18}
' Array literals with explicit type definition.
Dim articles() As String = { "the", "a", "an" }

' Array literals with explicit widening type definition.


Dim values() As Double = { 1, 2, 3, 4, 5 }
When you use type inference, the type of the array is determined by the
dominant type in the list of literal values. The dominant type is the type to
which all other types in the array can widen. If this unique type can’t be
determined, the dominant type is the unique type to which all other types in the
array can narrow. If neither of these unique types can be determined, the
dominant type is Object. For example, if the list of values that’s supplied to the
array literal contains values of type Integer, Long, and Double, the resulting
array is of type Double. Because Integer and Long widen only to Double,
Double is the dominant type. For more information, see Widening and
Narrowing Conversions.

VB

' Create and populate a 2 x 2 array.


Dim grid1 = {{1, 2}, {3, 4}}
' Create and populate a 2 x 2 array with 3 elements.
Dim grid2(,) = {{1, 2}, {3, 4}, {5, 6}}
When using nested array literals to create and populate an array, an error occurs
if the number of elements in the nested array literals don't match. An error also
occurs if you explicitly declare the array variable to have a different number of
dimensions than the array literals.
Just as you can for one-dimensional arrays, you can rely on type inference when
creating a multidimensional array with nested array literals. The inferred type is
the dominant type for all the values in all the array literals for all nesting level.
The following example creates a two-dimensional array of type Double[,] from
values that are of type Integer and Double.

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.

Iterating through an array


When you iterate through an array, you access each element in the array from
the lowest index to the highest or from the highest to the lowest. Typically, use
either the For...Next Statement or the For Each...Next Statement to iterate
through the elements of an array. When you don't know the upper bounds of the
array, you can call the Array.GetUpperBound method to get the highest value of
the index. Although lowest index value is almost always 0, you can call the
Array.GetLowerBound method to get the lowest value of the index.

The following example iterates through a one-dimensional array by using the


For...Next statement.

VB

Module IterateArray
Public Sub Main()
Dim numbers = {10, 20, 30}

For index = 0 To numbers.GetUpperBound(0)


Console.WriteLine(numbers(index))
Next
End Sub
End Module
' The example displays the following output:
' 10
' 20
' 30
The following example iterates through a multidimensional array by using a
For...Next statement. The GetUpperBound method has a parameter that
specifies the dimension. GetUpperBound(0) returns the highest index of the first
dimension, and GetUpperBound(1) returns the highest index of the second
dimension.

VB

Module IterateArray
Public Sub Main()
Dim numbers = {{1, 2}, {3, 4}, {5, 6}}

For index0 = 0 To numbers.GetUpperBound(0)


For index1 = 0 To numbers.GetUpperBound(1)
Console.Write($"{numbers(index0, index1)} ")
Next
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' Output
' 12
' 34
' 56
The following example uses a For Each...Next Statementto iterate through a
one-dimensional array and a two-dimensional array.

VB

Module IterateWithForEach
Public Sub Main()
' Declare and iterate through a one-dimensional array.
Dim numbers1 = {10, 20, 30}

For Each number In numbers1


Console.WriteLine(number)
Next
Console.WriteLine()

Dim numbers = {{1, 2}, {3, 4}, {5, 6}}


For Each number In numbers
Console.WriteLine(number)
Next
End Sub
End Module
' The example displays the following output:
' 10
' 20
' 30
'
' 1
' 2
' 3
' 4
' 5
' 6

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.

Size and Element Size


An array's size is independent of the data type of its elements. The size always
represents the total number of elements, not the number of bytes that they
consume in memory.
Memory Consumption
It is not safe to make any assumptions regarding how an array is stored in
memory. Storage varies on platforms of different data widths, so the same array
can consume more memory on a 64-bit system than on a 32-bit system.
Depending on system configuration when you initialize an array, the common
language runtime (CLR) can assign storage either to pack elements as close
together as possible, or to align them all on natural hardware boundaries. Also,
an array requires a storage overhead for its control information, and this
overhead increases with each added dimension.
The array type
Every array has a data type, which differs from the data type of its elements.
There is no single data type for all arrays. Instead, the data type of an array is
determined by the number of dimensions, or rank, of the array, and the data type
of the elements in the array. Two array variables are of the same data type only
when they have the same rank and their elements have the same data type. The
lengths of the dimensions of an array do not influence the array data type.

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

One-Dimensional Array And Two-Dimensional Arrays:-


Introduction to Arrays

By definition, an array is a variable with a single name that represents many


different items. When we work with a single item, we only need to use one
variable. However, if we have a list of items which are of similar type to deal
with, we need to declare an array of variables instead of using a variable for
each item. For example, if we need to enter one hundred names, it is difficult to
declare 100 different names. Besides, if we want to process those data that
involves decision making, we might have to use hundreds of if...then
statements, this is a waste of time and efforts.So, instead of declaring one
hundred different variables, we need to declare only one array. We differentiate
each item in the array by using subscript, the index value of each item, for
example, name(1), name(2), name(3) .......etc. , makes declaring variables more
streamline.

Dimension of an Array

An array can be one-dimensional or multidimensional. A one-dimensional array


is like a list of items or a table that consists of one row of items or one column
of items.
A two-dimensional array is a table of items that make up of rows and columns.
The format for a one-dimensional array is ArrayName(x), the format for a two
dimensional array is ArrayName(x,y) and a three-dimensional array is
ArrayName(x,y,z) . Normally it is sufficient to use a one-dimensional and two-
dimensional array, you only need to use higher dimensional arrays if you need
to deal with more complex problems. Let me illustrate the arrays with tables

Table 1. One dimensional Array

Student
Name(1) Name(2) Name(3) Name(4)
Name

Table 2. Two Dimensional Array

Name(1,1) Name(1,2) Name(1,3) Name(1,4)

Name(2,1) Name(2,2) Name(2,3) Name(2,4)

Name(3,1) Name(3,2) Name(3,3) Name(3,4)

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.

Declaring one dimensional Array

The general syntax to declare a one dimensional array is as follow:

Dim arrayName(subscript) as dataType

where subs indicates the last subscript in the array.

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)

CusNam CusNam CusNam CusNam CusName(


e(1) e(2) e(3) e(4) 5)

CusNam CusNam CusNam CusNam CusName(


e(6) e(7) e(8) e(9) 10)

The second way is to specify the lower bound and the upper bound of the
subscript using To keyword. The syntax is

Dim arrayName(lowerbound To upperbound) As dataType

Example 2

Dim Count(100 to 500) as Integer

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.

2.2 Declaring two dimensional Array

The general syntax to declare a two dimensional array is as follow:

Dim ArrayName(Sub1,Sub2) as dataType

Example 5

If you wish to compute a summary of students involve in games according to


different year in a high school, you need to declare a two dimensional array. In
this example, let's say we have 4 games, football, basketball, tennis and hockey
and the classes are from year 7 to year 12. We can create an array as follows:

Dim StuGames(1 to 4,7 to 12 ) As Integer

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)

Basket StuGame StuGame StuGame StuGames StuGames StuGames


ball s(2,7) s(2,8) s(2,9) (2,10) (2,11) (2,12)

StuGame StuGame StuGame StuGames StuGames StuGames


Tennis
s(3,7) s(3,8) s(3,9) (3,10) (3,11) (3,12)

Hocke StuGame StuGame StuGame StuGames StuGames StuGames


y s(4,7) s(4,8) s(4,9) (4,10) (4,11) (4,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:

Dim saleVol(1 To 4, 1 To 6) As Integer

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

*Note: the keyword vbTab is to create a space

The output is shown in the figure below:

Static and dynamic arrays

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:

' An array defined in a BAS module (with Private scope)


Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub

If you're creating an array that's local to a procedure, you can do everything


with a single 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:

ReDim Customers(1 To 1000) As String


Dynamic arrays can be re-created at will, each time with a different number of
items. When you re-create a dynamic array, its contents are reset to 0 (or to an
empty string) and you lose the data it contains. If you want to resize an array
without losing its contents, use the ReDim Preserve command:

ReDim Preserve Customers(2000) As String

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:

ReDim Cells(1 To 100, 10) As Integer


...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.

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:

Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimension


Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)

Arrays within UDTs

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

You might also like