Thursday 23 January 2014

Dynamic arrays



An array can hold more than one value. An array lets you address many data values through the same variable. Think of an array as a list (e.g., a list of usernames). You reference each item in this list with a common name and index number. The common name is the name of the array variable. The common name typically includes the prefix arr to denote that the variable contains data of the subtype Array. The index number is an integer subscript that denotes an item's relative location in the list. The indexes always increment sequentially, starting from 0. For example, if an array has three items, the indexes are 0, 1, and 2. The 0 index represents the first position, the 1 index represents the second position, and the 2 index represents the third position in the array.
There are two types of arrays:
Static arrays
Dynamic arrays
Static array has to be declared with the number of elements that the array can hold (i.e. arr(5)).  If we don’t know the number of elements to be stored in the array, then the dynamic array can be used.
Syntax:
Dim arr()
ReDim keyword should be then used to declare the number of elements that the array can hold.
Syntax:
Dim arr()
ReDim arr(3)
Example:
Dim arr()
ReDim arr(3)
    arr(0)=10
    arr(1)=15
    arr(2)=20
msg=""
For i=0 to 3
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

ReDim arr(4)
arr(4)=20
msg=""
For i=0 to 4
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next
msgbox msg
In the above example, array is initially sized with five elements.  Array elements with indices 0 to 5 are initialized and displayed using for loop.  The array is resized with ReDim keyword and then the added array element is initialized with the statement “arr(4)=20”.

Output before resizing the array:
dynamicarray1
Output after resizing the array:
dynamicarray2
We will use the Preserve keyword with the ReDim in the above example.
Dim arr()
ReDim arr(5)
    arr(0)=10
    arr(1)=15
    arr(2)=20
    arr(3)=25
msg=""
For i=0 to 4
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next

msgbox msg

ReDim Preserve arr(6)
arr(4)=20
msg=""
For i=0 to 4
    msg=msg&"Arr("&i&") : "&arr(i)&vbnewline
Next
msgbox msg
preserve
Output shows the array element values starting from Arr(0) to Arr(6).  Preserve keyword preserves the values of the array elements before ReDim statement.  Hence, if we resize the array with ReDim and add new elements does not erase the earlier values of the array.

Follow the steps below to use the dynamic arrays:

Declare the array with no size – Dim array_name()
Re-declare the size of the array with ReDim & Preserve – ReDim Preserve array_name(number of elements)

No comments:

Post a Comment