Arrays (for beginners) - QB64 Wiki

Arrays (for beginners)

From QB64 Wiki

Jump to: navigation, search

Arrays can be seen as a table of values stored in one variable. An array consists of a number of elements (or subscripts) where each element can store data.


You define an array using DIM in this manner:

DIM array(20) ' dimensions an array with 20 elements.

You can use up to eleven elements without DIMensioning (0 to 10).

Now you can use the array like you use an ordinary variable, but you have to show which element you are using like this:


array(1) = 12


Where 1 is the element and 12 is the data assigned.


The point of arrays is to be able to set a large number of data using a variable for the element instead of having to assign each element on your own. For example; you can:


DIM array(20) FOR element = 1 TO 20 array(element) = element * 2 NEXT


Which is much better than:


variable1 = 2 variable2 = 4 variable3 = 6 variable4 = 8

The arrays we have used so far only has one dimension, you can also define arrays with dimensions larger than one. You might want to use two dimensions or even more (QB 4.5 supports 60 dimensions), you only have to specify them like this:


  • DIM array(20,20) 'for two dimensions, 20*20 unique elements
  • DIM array(20,20,20) 'for three dimensions, 20*20*20 unique elements


You could for example do like this:


DIM array(20, 20) FOR element2 = 1 TO 20 FOR element1 = 1 TO 20 array(element1, element2) = element1 * element2 NEXT NEXT


Now array(3, 10) equals 30 while array(3, 5) equals 15. We've created a multiplication table!


Arrays are much more flexible than ordinary variables, and I'm sure you'll find plenty of use for them!


And that's the end of this tutorial!



More information: Take a look at LBOUND and UBOUND, two functions that become important if you DIM an array using TO (like DIM array(1 TO 20) specifying a range of elements between 1 and 20) or which becomes important in those cases where you simply don't know the number of elements, also take a look at OPTION BASE which lets you set the default lower boundary of arrays to 1 (otherwise the default is 0).

For more technical information, see Appendix: Arrays.


Navigation:

QB64 Tutorials

Go to Keyword Reference - Alphabetical

Go to Keyword Reference - By usage

Views
Personal tools