34
myInt=myArray(5)
This will set the value of myInt to the current value of column 5 in myArray.
Two-Dimensional Arrays
A two-dimensional array is an array that has more than one row, along with the
defined columns. A two-dimensional array is like a table, with a defined number of rows,
where each row has a defined number of columns. The following code snippet defined an
array using the default method.
DimmyArray(2,10)asInteger
The first dimension defines the number of rows in the array, while the second
dimension defines the number of columns in each row. In this example, the array has 3
rows, numbered 0 to 2, and each row has 11 columns, numbered 0 to 10, if Option Base
has not been defined. If Option Base 1 had been used, then the row indexes would range
from 1 to 2, and the column indexes would range from 1 to 10.
You can also define the lower and upper bounds of the array.
DimmyArray(1to2,1to10)asInteger
This definition would set the number of rows to 2, numbered 1 to 2 and the
number of columns to 10, numbered 1 to 10.
Two-Dimensional Array Indexes
To access the array elements you would use two indexes. The first index selects
the row, and the second index selects a column within that row.
myArray(1,5)=7
This code would set column 5 in row 1 to 7.
myInt=myArray(1,5)
This code would set myInt to the current value contained within column 5 of row 1
of myArray.
Multi-Dimensional Arrays
For arrays of three or more dimensions, you would use the same format as listed
above, taking into account the progression of the array dimensions. For a three-
dimensional array, the first dimension would be the row, the second the column, the third
would be the z-order, or depth, of each column. For example, to define a cube in space,
you would use the y,x,z format, where y defines the vertical axis, x defines the horizontal
axis and z defines the depth axis. To create an array in this format you could define the
array as DimmyCube(y,x,z)asInteger. MyCube(10,10,10) would create a cube
151
57
with 11 vertical units, 0 to 10, 11 horizontal units, 0 to 10 and 10 depth units, 0 to 10. To
access the center of the cube, you would use iCenter=myCube(5,5,5).
You will probably never need to use arrays of more than three dimensions, unless
you are doing some advanced mathematical calculations. However, if you need to use
higher-dimensional arrays, the same principles apply.
The following program illustrates creating and accessing a two dimensional array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
OptionExplicit
'Createatwodimensionalarray
DimAsIntegermyArray(1To2,1To10),i,j
'Loadsomedataintothearray
Fori=1To2
Forj=1To9
myArray(i,j)=Rnd*10
Next
Next
'Printdatainarray
Fori=1To2
Forj=1To9
Print"row:";i;"col:";j;"value:";myArray(i,j)
Next
Next
Sleep
End
Listing 12.1: arrayindex.bas
Analysis:
Line 4 creates a two-dimensional array with two rows, with each row
having ten columns. The working variables i and j are also declared on the same line.
Lines 7 through 11 load some random data into the array. A nested For-Next loop is the
common way to access multi-dimensional arrays. The variable i will select the row
indexes while the j variable will access the column indexes.
Lines 14 through 18 will print the values stored in the array. The format is identical
to the load code. The program is closed in the usual way.
When you run the program you should see the following output.
row:1col:1value:0
row:1col:2value:6
152
Online Change your PDF file Permission Settings to make it as easy as possible to change your PDF You can receive the locked PDF by simply clicking download and If we need a password from you, it will not be
break pdf password online; reader save pdf with password
42
row:1col:3value:2
row:1col:4value:8
row:1col:5value:6
row:1col:6value:5
row:1col:7value:4
row:1col:8value:9
row:1col:9value:8
row:2col:1value:7
row:2col:2value:2
row:2col:3value:9
row:2col:4value:7
row:2col:5value:5
row:2col:6value:3
row:2col:7value:0
row:2col:8value:1
row:2col:9value:4
Output 12.1: Output of arrayindex.bas
Dynamic Arrays
The arrays described above are static arrays; the array size cannot change during
program execution. You can also create dynamic arrays that can change size during
execution. Dynamic arrays are useful for creating data structures such as stacks or
queues.
In order to use dynamic arrays in your program you need to include the Option
Dynamic directive in your program. Static arrays, the arrays described above, are kept on
the heap, but dynamic arrays are allocated from the computer's pool of memory so
Option Dynamic is needed to tell the compiler to dynamically allocate the array. You can
dimension a dynamic array in two ways. The first is to declare the array size in the Dim
statement and then resize it using Redim or RedimPreserve. The second is to not specify
the array size, use empty parenthesis, and then use Redim or Redim Preserve to size the
array. Redim will size the array and clear the array contents. Redim Preserve will size the
array and keep any existing data in th array.
There are a couple of exceptions to this. When declaring an array using variables for the
index values, the array is implicitly dynamic. You can also declare an array without
specifying index values, that is using an empty parentheses in the array declaration,
and then use Redim to resize the array without specifying Option Dynamic.
The following program creates a simple integer stack and then manipulates
the stack.
1
2
OptionExplicit
OptionDynamic
153
Online Remove password from protected PDF fileOnline Remove Password from Protected PDF file. Download Free Trial. Remove password from protected PDF file. Find your password-protected PDF and upload it.
pdf password reset; add password to pdf file with reader
86
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
'Createanintegerstack.The0indexwillbeouremptymarker.
DimAsIntegerstack(0),top=0,i,ivalue
'Thiswillpushavalueonthestack,updatethetopofstack
SubPushValue(astack()AsInteger,stacktopAsInteger,valueAsInteger)
'Incrementthetopofthestack
stacktop+=1
'Resizethestack
RedimPreserveastack(stacktop)
astack(stacktop)=value
EndSub
'Thiswillpopavalueoffthestack,updatetopofstack
FunctionPopValue(astack()AsInteger,stacktopAsInteger)AsInteger
DimAsIntegerret
Ifstacktop=0Then
ret=0
Else
ret=astack(stacktop)
stacktop=1
RedimPreserveastack(stacktop)
EndIf
Returnret
EndFunction
'Pushfivevaluesontostack
Print"Pushingvaluesonstack..."
Fori=1To5
ivalue=i*2
PushValuestack(),top,ivalue
Print"Stacktop:";Ubound(stack),"Value:";ivalue
Next
Print
'Popthevaluesoffthestack
Print"Poppingvaluesfromstack..."
ivalue=PopValue(stack(),top)
DoWhileivalue>0
Print"StackValue:";ivalue
ivalue=PopValue(stack(),top)
Loop
Print
'Checkstacksize
154
33
48
49
50
51
Print"Stacksizeafterpops:";Ubound(stack)
Sleep
End
Listing 12.2: stack.bas
Analysis:
In line the Option Dynamic directive is used to create the stack array
using dynamic memory. Line 5 dimensions the working variables. The 0 index in the stack
array will be used to indicate that the stack is empty. Even though this wastes one
integer, it makes the code easier to implement. Line 8 through 14 defines the code to
push a value on to the the stack. The parameters of the subroutine are the stack array,
the top-of-stack variable, and the value to push on to the stack. You could determine the
top of the stack using the Ubound function, however in a real stack implementation, you
will probably need to pass the top-of-stack to other functions, and keeping the value in a
variable will reduce the number of calculations the program must do.
Line 10 increments the stack top variable, and line 12 uses Redim Preserve to
resize the array, while keeping the existing data in the array. Line 13 set the new array
location to the value passed to the subroutine.
Line 16 through 27 pops the top value of the stack, if the stack index is grater than
zero, updates the top-of-stack variable and then returns the popped value. Line 19 and
20 checks to make sure that the stack has some data. If the index is 0, the stack is
empty. Lines 22 through 24 get the current value of the top stack item, updates the stack
pointer variable and then resizes the stack using Redim Preserve. Lines 31 through 35
use a For-Next loop to push 5 values on to the stack. Lines 40 through 44 pop the values
off the stack. A Do-Loop is used to pop the values since when the stack is empty, the
return value will be 0. Line 48 then cheks to see if all the values have been popped from
the stack.
The program is closed in the usual way.
When you run the program you will see the following output.
155
48
Pushingvaluesonstack...
Stacktop:1Value:2
Stacktop:2Value:4
Stacktop:3Value:6
Stacktop:4Value:8
Stacktop:5Value:10
Poppingvaluesfromstack...
StackValue:10
StackValue:8
StackValue:6
StackValue:4
StackValue:2
Stacksizeafterpops:0
Output 12.2: Output of stack.bas
Stacks have a wide range of uses, however most implementations use pointers
since it is much faster to manipulate a pointer than it is an array. The advantage of an
array is the simplicity of use, and the readability of the code, but if you need speed, you
should use a pointer memory array for stacks.
You can only Redim or Redim Preserve the first index, that is the row, in a
multidimensional array.
Array Functions
There are a number of functions that you can use to manage arrays. The following
table lists the array functions available in FreeBasic.
Function
Syntax
Comment
Clear
Clear array, value,
num_bytes
Sets num_bytes in array to
byte value.
Erase
Erase array
Erases dynamic arrays from
memory, or clears static
arrays.
Lbound
B = Lbound(array)
B = Lbound(array,
dimension)
Returns the lowest index of
a single or multidimensional
array. The dimension
parameter is the dimension
to check in a
multidimensional array
where the first dimension is
156
72
Function
Syntax
Comment
1, the second dimension is
2, and so on.
Option Dynamic
Option Dynamic
Allocates arrays into
dynamic memory by
default.
Option Static
Option Static
Clears a previous Option
Dynamic. All subsequent
arrays will be allocated on
the heap.
Preserve
Redim Preserve
Preserves data in an array
when resized using the
Redim statement.
Redim
Redim array(dimensions) as
DataType
Resizes an array to size
dimensions.
Ubound
B = Lbound(array)
B = Lbound(array,
dimension)
Returns the highest index of
a single or multidimensional
array. The dimension
parameter is the dimension
to check in a
multidimensional array
where the first dimension is
1, the second dimension is
2, and so on.
Table 12.1: Array Functions
Out of all the functions, you will probably use the Lbound and Ubound functions
the most, especially when working with dynamic arrays. The following program uses both
functions to get the size of a two dimensional array.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
OptionExplicit
OptionDynamic
'Createadynamicarray
DimAsIntegermyArray(),i,nb
'Resizearraywithtwodimensions
RedimmyArray(1To1,1To5)
'Printupperandlowerboundsforeachrowandcolumn
Print"FirstRedim"
Print""
Print"MinRowIndex:";Lbound(myArray,1);
Print"MaxRowIndex:";Ubound(myArray,1)
Print"MinColumnindex:";Lbound(myArray,2);
Print"MaxColumnindex:";Ubound(myArray,2)
157
56
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
Print
Print"AdditionalRedims"
Print""
'Redimarrayfivetimes
Fori=1To5
nb=Ubound(myArray,1)+1
RedimmyArray(1Tonb,1To5)
'Printnewarraysize
Print"MinRowIndex:";Lbound(myArray,1);
Print"MaxRowIndex:";Ubound(myArray,1)
Print"MinColumnindex:";Lbound(myArray,2);
Print"MaxColumnindex:";Ubound(myArray,2)
Print
Next
Sleep
End
Listing 12.3: ulbound.bas
Analysis: Line 2 set the compiler directive Option Dynamic so that the array is
allocated in dynamic memory. Line 5 creates a dynamic array with no dimensions
specified. Line 7 uses Redim to create a two-dimensional array. Lines 10 through 15 print
the upper and lower bounds using Lbound and Ubound respectively. Notice that the
dimension parameter is used to specify which dimension to get the lower and upper
bounds. 1 is used to get the bounds for the first dimension, and 2 is used to get the
second dimension.
Lines 20 through 29 resize the first dimension of the array and print the new lower
and upper indexes. Line 21 gets the current upper bound of the first dimension, 1 is
added to that value and then Redim is used in line 22 to resize the first dimension of the
array. Lines 24 through 27 get the new bounds and print the values to the screen.
The program is closed in the usual way.
When you run the program you should see the following output.
FirstRedim
MinRowIndex:1MaxRowIndex:1
MinColumnindex:1MaxColumnindex:5
AdditionalRedims
MinRowIndex:1MaxRowIndex:2
MinColumnindex:1MaxColumnindex:5
158
35
MinRowIndex:1MaxRowIndex:3
MinColumnindex:1MaxColumnindex:5
MinRowIndex:1MaxRowIndex:4
MinColumnindex:1MaxColumnindex:5
MinRowIndex:1MaxRowIndex:5
MinColumnindex:1MaxColumnindex:5
MinRowIndex:1MaxRowIndex:6
MinColumnindex:1MaxColumnindex:5
Listing 12.4: Output of ulbound.bas
The first Redim sets the initial bounds for the array. The additional Redims increase
the number of rows in the array, while leaving the number of columns in intact. Keep in
mind that arrays in FreeBasic are table-like, where each row has the same number of
columns. Ragged arrays, where each row has a different number of columns, cannot be
created in FreeBasic using arrays. You would have to use pointers to create a ragged
array.
Arrays of Types
Type definitions allow you to group related data into a single entity, and often you
will need more than one instance of a type to fully express the data. Arrays of types allow
you create multiple instances of a type definition that can be easily managed using the
arrays functions. An example of this usage may be an inventory system for your RPG, a
series of document descriptions within an editor, and a set of employee records from a
random access database.
You create arrays of types just as you would with any of the intrinsic data types.
The following code snippet illustrates the syntax.
TypemyPoint
xAsInteger
yAsInteger
EndType
TypemyLine
p1AsmyPoint
p2AsmyPoint
charAsString*1
EndType
DimmyLineSet(1to3)asmyLine
159
81
The code defines a set of 3 lines, with endpoints p1 and p2, where each endpoint
is located at row and col. The following program illustrates using this definition to print
some lines to the console screen.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
OptionExplicit
'Definethepoint
TypemyPoint
xAsInteger
yAsInteger
EndType
'Definetheline
TypemyLine
p1AsmyPoint
p2AsmyPoint
charAsString*1
EndType
'Createasetof3lines
DimmyLineSet(1To3)AsmyLine
DimAsIntegeri
'ThissubroutineusestheBresenhamLinealgorithm
'toprintalineontheconsolescreen.Google
'"BresenhamLinealgorithm"formoreinformation.
SubDrawLine(aLineAsmyLine)
DimAsIntegeri,deltax,deltay,num
DimAsIntegerd,dinc1,dinc2
DimAsIntegerx,xinc1,xinc2
DimAsIntegery,yinc1,yinc2
DimAsIntegerx1,y1,x2,y2
'Gettheendpointcoordinates
x1=aLine.p1.x
y1=aLine.p1.y
x2=aLine.p2.x
y2=aLine.p2.y
'Getthedeltachangeinbothxandy
deltax=Abs(x2x1)
deltay=Abs(y2y1)
'Calculatetheslopeoftheline
Ifdeltax>=deltayThen
160
Documents you may be interested
Documents you may be interested