Tuesday, April 8, 2008

Structures

Instead of using parallel or 2-dimensional arrays for storing various information that we would like to manipulate. For example, universities have various information about them that is universal. Each university has the following properties:

  • Name
  • State in which the university is located
  • Date that the university was founded
  • Population


Of course there are many more things that universities have, but this is a start.

Now we could use parallel arrays to store this information (like in our ATM project). Doing so, would mean that we would have 4 arrays to store the above information and that we could use the same index to reference information for a particular university:

Dim uName(3) As String
Dim uState(3) As String
Dim uFounded(3) As String
Dim uPopulation(3) As String

Let's say that we set the following:

uName(1) = "Queens College"
uState(1) = "NY"
uFounded(1) = "1960" 'I'm not sure about the date
uPopulation(1) = "5,000" 'Or the population :-)

So all of Queens College's information is accessible by accessing index 1 of each array. Thus the parallel Nature.

But suppose that we do not want to keep track of four arrays. We could then create a Structure or a container to keep all of this information in one place:

Structure uInfo
Dim name As String
Dim state As String
Dim founded As String
Dim population As String
End Structure

Now we have created our own type and we can declare a variable of this type like this:

Dim college As uInfo

In order to set (or use) any property of colleges, we use the ``dot'' method:

college.name = "Queens College"
college.state = "NY"
college.founded = "1960"
college.population = "5,000"


Declaring an Array of type uInfo

We can declare arrays of any type, including our own defined types.

Dim colleges(10) As uInfo
colleges(0).name = "Queens College"
colleges(0).state = "NY"
colleges(0).founded = "1960"
colleges(0).population = "5,000"

The resulting array will look like (except up to 10):
        0          1    2 ...
+---------------+----+----+
| Queens College| | |
+---------------+----+----+
| NY | | |
+---------------+----+----+
| 1960 | | |
+---------------+----+----+
| 5,000 | | |
+---------------+----+----+


You can see that every cell is broken up into 4 parts that contain the items from the structure itself.

Of course if we had an array of things, it would make more sense to take in the information from a file:

For i As Integer = 0 To 10
colleges(i).name = sr.Readline()
colleges(i).state = sr.Readline()
colleges(i).founded = sr.Readline()
colleges(i).population = sr.Readline()
Next

No comments: