Page 1 of 1

array example

Posted: 17 March 2007, 14:18 PM
by hacktorious
Could somebody please give me an example of how to access the contents of an array?

I have the following:
someNumbers(12345, 56456, 123432, 12324)

I would like to use this array in a loop and iterate through it, but when I try to access an individual index I get an error.

For example:

For counter = 1 To 4
Consol.Write(someNumbers(counter))
Next counter

Thanks.

Also, is it possible to populate an array one index at a time while iterating a loop?

Re: array example

Posted: 17 March 2007, 17:21 PM
by dkinzer
hacktorious wrote:Could somebody please give me an example of how to access the contents of an array?
Here is code for accessing a 1-dimension array:

Code: Select all

Dim data(1 to 20) as Byte

Sub Main()
  Dim i as Byte
	
  ' populate the array
  For i = 1 to 20
    data(i) = i * 10 + 5
  Next i
	
  ' display the array contents
  For i = 1 to 20
    Debug.Print "data("; CStr(i); ") = "; CStr(data(i))
  Next i
End Sub
Note that in the definition of the array "data" the range of the single index was specified as 1 to 20. It is not necessary for the lower bound to be 1 but that is probably the most commonly used lower bound. RAM-based arrays can only be populated with data by writing code to do it at run time.

This idea can be extended to a multi-dimension array by adding additional indices to the definition and the accesses.

Re: array example

Posted: 17 March 2007, 17:35 PM
by dkinzer
hacktorious wrote:I have the following:
someNumbers(12345, 56456, 123432, 12324)
I'm not quite sure what you meant by this. Did you intend to define a 4-dimension array or a 1-dimension array with 4 elements? I suspect that your intention was the latter and you also wanted to initialize the array with the 4 values shown. For a RAM-based array, you'd have to write code to set the four values, e.g.

Code: Select all

Dim someNumbers(1 to 4) as Long
someNumbers(1) = 12345
someNumbers(2) = 56456
someNumbers(3) = 123432
someNumbers(4) = 12324
Then, the code to display the values would be:

Code: Select all

Dim counter as Integer
For counter = 1 To 4
      Console.Write(CStr(someNumbers(counter)))
Next counter
Note here that the CStr() function was used to convert the numeric value to a string since Console.Write() requires a string argument.

If the data values never change, you can use a Program Memory data item and provide compile-time initialization for it like this:

Code: Select all

Dim someNumbers as LongVectorData ({12345, 56456, 123432, 12324})

Sub Main()
  Dim counter as Byte
	
  For counter = 1 to CByte(UBound(someNumbers))
    Console.Write(CStr(someNumbers(counter)))
  Next counter
End Sub

Posted: 19 March 2007, 18:22 PM
by hacktorious
Yes, was improperly initializing the array. It works great now, thanks.