You can (unformally) think of arrays as lists. Or, if you're familiar with the concept in math, sets.
These two pieces of code are identical, for a finite number of practical purposes:
Code: Select all
'' our list of numbers
dim as integer foo1 = 0
dim as integer foo2 = 5
dim as integer foo3 = 10
dim as integer foo4 = 15
dim as integer foo5 = 20
'' our highest number
dim as integer highest = 0
'' find our highest number
if( foo1 >= highest ) then highest = foo1
if( foo2 >= highest ) then highest = foo2
if( foo3 >= highest ) then highest = foo3
if( foo4 >= highest ) then highest = foo4
if( foo5 >= highest ) then highest = foo5
Code: Select all
'' our list of numbers
dim as integer foo(0 to 4)
for i as integer = 0 to 4
foo(i) = i*5
next
'' our highest number
dim as integer highest = 0
'' find our highest number
for i as integer = 0 to 4
if( foo(i) >= highest ) then highest = foo(i)
next
Where
foo(i) means, in laymen terms, "Get me the
i'th number from the list foo".
In programming, we say this more generally as, "Return, get, or access the variable in the
i'th index of foo()".
How familiar are you with algebra? I can explain the benefit of using foo(i) over
foo1, foo2, ..., fooN in algebraic terms, because it's just like the benefits of algebra over elementary arithmetic.
In arithmetic, we say this:
4 + 5 = 12. Cool, but what if we wanted to add another number, or change the numbers we add? We'd have to change both sides of our equation. This is like using an if statement for each variable you create. Very unintuitive:
Code: Select all
dim as integer foo1 = 0
dim as integer foo2 = 0
if( foo1 > foo2 ) then print "foo1 > foo2"
dim as integer foo3 '' uh oh, now I need another if statement!
if( foo3 > foo2 ) then print "foo3 > foo2"
Algebra, however, says: a + b = c. Use any integers as a or b and we will always get integer c. This allows us to introduce the concept of algorithms - general methods of algebraic problem solving. Here's an example:
for all integers i in set foo, let a be the sum of i. Or, in code:
Code: Select all
'' create our list, or set foo. We call these arrays in programming.
dim as integer foo()
'' create a randomly sized array, from 1 to 40 elements. 0 is the first index of our array.
'' rnd() means random and always returns a value less than 1.
redim foo(0 to rnd() * 40)
'' fill our array with random data - ubound(array) gives us the last index of an array. lbound(array) gives us the first index, but we don't need it here.
for i as integer = 0 to ubound(foo)
foo(i) = rnd() * 100
next
'' get the sum of all elements in array foo
dim as integer a = 0
for i as integer = 0 to ubound(foo)
a += foo(i)
next
'' print our sum
print "The sum of all integers in array foo: " & a
sleep
Instead of writing rules for one, two, etc. integers, we can write code which will work with
any number of integers. Arrays help us do this.