Monday, 14 October 2013

VB Lesson 8: One Dimensional Array

Onto one dimensional arrays. This is a fairly easy idea and a particularly useful function. Although forgive me if I make any mistakes, I am exceedingly tired. I hope you're going to watch Made in Chelsea tonight Lalin, it promises to be a good start to the series ;).

Visual Basic Lesson 8:

So, here we are at arrays. There are other arrays, but we first need to learn about one dimensional arrays. Essentially a one dimensional array is a data structure that can be used to store a collection of data of the same data type. Of the same data type? Does that mean you cannot store string and integer together? Well, yes it does when it comes to one dimensional arrays, if you want to store a collection of different data types, you have to use a record.

It's not particularly complicated and there's nothing special. The way to use a one dimensional array is the same as any other function. Essentially you use a variable declaration as usual, but you have to specify the number of elements. For example:

Dim list(10) As Integer

As you can see, you are still giving the variable an identifier and you're still specifying the data type, but you're also telling it just how much data you're going to store.

Along with elements you also have indexes. The indexes are the numbers given to each array element. Once you have declared the data each element is initialised to zero and this only changes once the data has been inputted by a user. 

One dimensional arrays generally go hand it hand with For Next loops. This is so that you don't have to create several lines of the same code for each element in an array. For example:

Dim list(5) As Integer

list(1) = InputBox("Enter a value")
list(2) = InputBox("Enter a value")
etc...

Where as a For Next loop prevents this untidy time wasting practice:

Dim list(5) As Integer
Dim x As Integer

For x = 1 to 5
List(x) = InputBox("Enter a value")
Next x

This code looks neat and makes sense, it allows the you to collect the data you need in a simple piece of coding.

Here are some more example programs created in class:

The above program is a program which takes 10 pieces of data inputted by the user and then displays them in a MsgBox in reverse order.

Another example of the program being used to a For Next loop:

This is a piece of coding which takes the numbers that the user inputs and it then squares them.

And another:


This program shows the use of a For Next loop with an array to shift the inputted data one element to the left.

And final example:

This program shows the real skill of the array data structure. It shows two arrays having their data inputted separately, but then being added together to create the data for a third array.

And this really concludes arrays. Sorry it wasn't really great, but I am feeling exceedingly tired today, I might come back to update this.
Until next time ;).

No comments:

Post a Comment