Basic Introduction To Arrays, Conditionals & For…Next Loop in VB.Net

Simon Ugorji
10 min readApr 7, 2023
Story VB.NET cover photo

It’s been a while since I wrote & published my last article 😥

I was asked to help out on a VB.Net assignment and this made me learn the basics of VB.Net. With my knowledge of JavaScript and PHP, I was able to quickly understand the concepts, and I decided to document them so as to make them easy to understand.

We will begin by discussing what an array is, what an array index is, and how to create an array.

Before I begin, I want to let you know that I am open to Web Development and Technical Writing roles 😊

WHAT IS AN ARRAY

An array is used to store a collection of data at contiguous memory locations.

It is mostly used to store data of the same type. For instance, you can use an array to store the names of people in a class, their ages, and even their marks in a particular assessment.

To create an array in VB.Net, we use the Dim keyword and then we provide a pair of brackets. Inside these brackets, we can specify the number of elements the array can hold i.e if we are creating a fixed-size array or we can leave it empty i.e if we are creating a dynamic array.

Here’s an example;

Dim num(4)
'Dim is the keyword used to create the array
'num is the name of the array
'4 is the fixed size of this array and this means that the array can hold up to 5 elements.

The example above creates an array of 5 elements with the indices running from 0–4.

Now, we cannot talk about arrays without first knowing what an index is.

WHAT IS AN INDEX

Simply put, an index is the position of an element in a collection. You can also say that it is the number given to a particular element based on its position in a collection.

In most programming languages, indexing starts at 0 and not 1 and this means that the first element in a collection will have an index of 0, and the last element in that collection will have an index of (Total number of items in the collection — 1).

Here’s a better explanation;

From the code above, we created an array of numbers that will hold up to 5 elements and this means that the first element of this array will have an index of 0 and the last element will have an index of (Total number of items in the collection — 1) which is 5–1 = 4.

WHAT’S THE USE OF AN INDEX?

Well, we use an index to retrieve the element at a particular position in an array.

This means that if you have an array of numbers and you wish to know the element at position 1, you can write a code that will return the element at that position, using index 1.

Here’s an example

Dim numbers(4) As Integer 'Create an array of numbers of type integer

'Store elements in the array from index 0 to 4
numbers(0) = 1 'This is position 0
numbers(1) = 2 'This is position 1
numbers(2) = 3 ' ...
numbers(3) = 4 ' ...
numbers(4) = 5 'This is position 4

Console.Write("The number at position 1 is {0}", numbers(1)) 'Retrieve the element at position 1

If you compile the code above, you will see a similar output below.

Now, let us talk about the types of arrays in VB.Net

TYPES OF ARRAY

In VB.Net, there are 2 types of array

  1. Fixed-size Array
  2. Dynamic Array

FIXED-SIZE ARRAY

The fixed-size array is an array whose size has already been defined. This means that if we create an array and then specify the size of this array, the array can only store elements until the size specified is reached.

For instance, consider the code below;

Dim numbers(4) 

'Dim is the keyword used to create the array
'numbers is the name of the array
'4 is the fixed size of this array and this means that the array can hold up to 5 elements.

The numbers array has been created to store up to 5 elements and this means that we can add 1,2,3,4,5 to the array. If you try to add any more element to this array, it will throw an error because we had already specified its size which is 5.

It is also important to note that if you create a fixed-size array of data-type integer, it automatically gets filled with zeros until you replace the elements.

DYNAMIC ARRAY

The Dynamic array is an array that does not have its size already defined and this means that we can change the size of this array at run-time (i.e. the size of a dynamic array can change during program execution).

To change the size of a dynamic array, we use the ReDim keyword.

Here’s an example;

'Create a numbers array without specifying the size
Dim numbers()

'Resize the numbers array to store 5 elements
ReDim numbers(4)

But there’s an issue with the implementation above.

What if we created an array of numbers 1–5 and then we wanted to add more numbers 6–10 to this array, how do we increase the size of this array to hold up to 10 elements?

This brings us to the ReDim statement.

Let’s talk about the ReDim Statement

Consider the code below;

Dim numbers(4) As Integer 'Create array that will hold up to 5 elements

numbers(0) = 1 'This is position 0
numbers(1) = 2 'This is position 1
numbers(2) = 3 ' ...
numbers(3) = 4 ' ...
numbers(4) = 5 'This is position 4

Redim numbers(9) 'Resize the array to hold up to 10 elements

numbers(5) = 6 'This is position 5
numbers(6) = 7 'This is position 6
numbers(7) = 8 ' ...
numbers(8) = 9 ' ...
numbers(9) = 10 'This is position 9

For i As Integer = 0 To numbers.length - 1

Console.WriteLine(numbers(i)) 'Loop through the array and print its elements

Next i

If you run the code above, you will notice that when we resized the array, its initial values were lost in the process, and this leaves us with 6–10.

Luckily, there’s a way to preserve the initial value of an array when we choose to resize it.

To retain the initial value of an array when resizing it, we need to use the Preserve keyword along with the ReDim statement.

ReDim Preserve numbers(9) 'This will increase the size of the array and still retain its initial value

To correct our code above, this is what we can do;

Dim numbers(4) As Integer 'Create array that will hold up to 5 elements

numbers(0) = 1 'This is position 0
numbers(1) = 2 'This is position 1
numbers(2) = 3 ' ...
numbers(3) = 4 ' ...
numbers(4) = 5 'This is position 4

Redim Preserve numbers(9) 'Resize the array to hold up to 10 elements while preserving initial values

numbers(5) = 6 'This is position 5
numbers(6) = 7 'This is position 6
numbers(7) = 8 ' ...
numbers(8) = 9 ' ...
numbers(9) = 10 'This is position 9

For i As Integer = 0 To numbers.length - 1

Console.WriteLine(numbers(i)) 'Loop through the array and print its elements

Next i

If you run the code above, you will see the expected output

Having explained the ReDim statement, let’s go back to our array.

We can also set the data type of our array, which means that the array will only store elements of that data type.

Here’s an example;

'This means that the array will store up to 5 integers
Dim numbers(5) As Integer

'This means that the array will store up to 5 strings
Dim names(5) As String

Now, let us talk about the For…Next loop in VB.Net

For…Next Loop

Before we talk about this type of loop, I want to first make sure that you understand what a loop is.

What is a loop

A loop is a sequence of instructions continually repeated until a specified condition is reached.

Now, the For…Next Loop is a type of loop that is used to repeatedly execute a block or sequence of code until a condition is satisfied.

Here’s the syntax

'Syntax for For...Next loop
For [variable_name] As [data_type] = [start] To [end] step [step]

[statements_to_execute]

Next [variable_name]

Here’s an explanation

  • For: It is the keyword that is present at the beginning of the loop
  • [variable_name]: This is the name of the variable which is required in the statement. The value of this variable determines when to exit from the For-Next loop and its value should only be numeric.
  • [data_type]: It represents the Data Type of the variable.
  • [start] To [end]: The start and end are the two important parameters representing the initial and final values of the variable. When the execution begins, the initial value of the variable is set by the [start].

    Before the completion of each repetition, the variable’s current value is compared with the [end] value. And if the value of the variable is less than the [end] value, the execution continues until the variable’s current value is greater than the end value. And if the value is exceeded, the loop is terminated.
  • Step: A [step] parameter is used to determine by which the counter value of a variable is increased or decreased after each iteration in a program. If this value is not specified; It uses 1 as the default value.
  • Statements: A statement can be a single statement or group of statements that execute during the completion of each iteration in a loop.
  • Next: In VB.NET a Next is a keyword that represents the end of the loop

Here’s an example of a For…Next loop

To count from 1–10, we will write a For…Next loop with a counter with the initial value of 1 and then we will increment this counter by 1 (using step 1) until 10 is reached and when the value of this counter is greater than 10, the loop will be terminated.

For i As Integer = 1 To 10 step 1

Console.WriteLine(i)

Next i

I hope my explanations are clear enough.

Now, let us talk about conditional statements

The If…Then Conditional Statement

A conditional is an expression that is evaluated to be either true or false.

We can create an If…Then conditional in VB.Net by following the syntax below

If [expression] Then

[statements_to_execute]

EndIf

If we want to keep checking the expression for another value we can add more conditionals by using the ElseIf keyword.

Here’s an example

Dim username As String = "Simon" 'Create a variable that will store the username

If (username = "Tony") Then 'Check if username is Tony

Console.Write("You are not authorized") 'Print result

ElseIf (username = "Simon") Then 'Check if username is Simon

Console.Write("You are authorized") 'Print result

End If 'End the If statement

When you run the code you will see a similar output below

It is also important to note that only one equality sign is needed to compare values. You can read more about comparison operators here

It’s Play Time!

We will create an array even that will store even numbers from 1 to 20.

This array will have a predefined size of -1 and by so doing, the length of the array is 0.

Then we will use a For…Next loop to count from 1 to 20 and then check if each number is an even number using the modulo operator Mod .

Assuming we do not know how many even numbers are between 1 to 20, we will resize this array to accommodate the numbers while preserving the initial elements using the ReDim keyword.

After the first loop is completed, we will create another loop that will display the elements in our array and these elements are the even numbers between 1 to 20.

Module Test
Sub Main()
'How to use the ReDim statement to resize an array
'Create an array that will store even numbers from 1 to 20 and then resize accordingly to
'accomodate the even numbers from 1 to 20

Dim even(-1) As Integer 'Create array that will store Integers. The length changes dynamically

For i As Integer = 1 To 20 'Check even numbers from 1 - 20

If (((i Mod 2)) = 0) Then

ReDim Preserve even(even.length) 'Resize the array to add more size based on whether the current index is an even number

even(even.length - 1) = i 'Store the current index to the array

End If

Next i 'Terminate if i is greater than 20

For j as Integer = 0 To (even.length - 1)

Console.WriteLine(even(j))

Next j 'Terminate if j is greater than the length of even.length - 1

Console.Write("There are {0} Even numbers from 1 to 20", even.length)

End Sub
End Module

If you run the code above, you will see a similar output below;

EXTRA

I have been using 2 console methods; WriteLine and Write to print text to the console. Here’s the difference between the 2 methods above.

WriteLine

This method prints text to the console by adding a new line character to the end of the text. This means that the text printed will be on a new line.

Write

This method prints text to the console and does not add a new line character to the end of the text. This means that the text printed will be in the same line.

CONCLUSION

We discussed about arrays, their types, and how to create arrays in VB.Net. We also discussed about an array index, what an index is, and the use of an index.

Next, we talked about what a loop is and how we can create a For…Next loop in VB.Net

Finally, we wrote a code that combines an array, a conditional statement, and a loop just to make sure that it is clear.

You can read more on this language through the links below

Mircosoft

TutorialsPoint

JavaTPoint

I would appreciate any feedback or corrections on the article above.

Thank you for reading.

--

--

Simon Ugorji

Full-Stack Web Developer And Technical Writer On PHP & JavaScript