Sunday, May 22, 2011

Beginning Programming with Just BASIC -- Tutorial 5: Arrays



Tutorial 5: Arrays

Arrays are similar to variables, except that they can hold more than one value. For instance, a list of names and grades. This is a good way to organize data, especially when little is known about the data that is going into them, in particular how many data point there are.

To set up an array in your program requires a little more work than it takes to use a variable. First you have to define how big the array will be, that is, how many values it can hold. You do that with the DIM command:

dim myArray(100)

In parentheses you put a number defining the size of the array. In this case I can put 100 values into the array called myArray(). So how do I do that?

With loops! Arrays are often used in conjunction with FOR loops because of how easy it is to systematically define every value.

for i = 1 to 100
    input myArray(i)
next

This is far easier than having to write out

input myArray(1)
input myArray(2)
input myArray(3)...

You get the picture.

You can also have multidimensional arrays. Say you want to associate two parameters to the same value. You can do that easily:

dim twoDimensional(10,10)
for i = 1 to 10
    for j = 1 to 10
        twoDimensional(i,j) = i*j
    next
next

Those are the essentials of making an array. I decided to include them early on so you don't waste time trying to use variables for some complex program.

goto [nextTutorial]

2 comments:

  1. Thanks man! I finally get arrays. :D

    ReplyDelete
  2. How would you make an array that had 4 things you wanted to access randomly? Basically, how do you randomly access things from a dim array?

    ReplyDelete