Array Basics

By: Kevin Picone



What are they?

      To understand Arrays, is to understand the difference between managing individual items like Variables and collections of items (Arrays).

      So conceptually,


Variables can only hold a single piece of information. This information can either be a 'value' or 'string' (text information).

Arrays on the other hand, allow us to store entire collections of values or strings (text information) inside each array container. You can imagine them much like the filing cabinets in our programs, where we can store & retrieve data as we need it.




I N D E X:







Lets Begin


      To help get our minds around this new concept, this tutorial will run through a situation where we'd choose arrays over variables. Not sure what a Variable is ? Well, make sure you read the Variables tutorial first ! If you're already up to speed, then lets press on !


      Imagine you have a list of High Scores values in your game. While you could use separate variables to store each high score value, this tends to get messy when we have lots of individuals pieces of data. While you could do it this way, it's not recommended !


      Example. If you used variables to hold and display your top 5 high scores, our code might look something like this.

  
  
; assign each highscore variable it's starting value
  HighScore1 = 100000
  HighScore2 = 90000
  HighScore3 = 80000
  HighScore4 = 70000
  HighScore5 = 60000
  
; display the high scores to the screen
  Print HighScore1
  Print HighScore2
  Print HighScore3
  Print HighScore4
  Print HighScore5
  
; display the screen and wait for a key press
  Sync
  WaitKey
  



      Now there's nothing really wrong with that, but it's just not very flexible for us in the long term. Imagine if we had 100 high scores values. That's a lot of variables to create and maintain. So this becomes a perfect opportunity for using an array. Since arrays by design, allow us to store and manipulate collections of data inside them.


      We create an Array using the DIM (dimension) command. Dim requires at least two things in order to create an array successfully. The first is the Name of the our array and the second is the size.


i.e.

  
  Dim MyArrayName(size)
  


      So getting back to our High Score table example, what we could do is Dimension an array called HighScores. Then use this array to hold all of high score values. Now since the example above uses five high scores, then we'll make our array big enough to hold five values also.


Example
  
  Dim HighScores(5)
  



      Here we've dimensioned our HighScore array with enough space to contain our five pieces of data in it.

      The following table is a visual representation of how the HighScores array is internally laid out. The top row of the table represents the cell index. These index will range from zero to the five, the bottom is data stored in each cell. Initially the cell will be empty (equal 0).


High Scores Array Contents Table
  
  ------------------------------------------------
  Cell#|    0 |    1 |    2 |    3 |    4 |    5 |
  ------------------------------------------------
  Data |    0 |    0 |    0 |    0 |    0 |    0 |
  ------------------------------------------------
  


Top






How do I access array information ?


      To access individual cells within an array, we use what is called an INDEX. An index is the number of the element you wish to examine. So using indexes we can selectively access any of the available items inside an array.


Example. (Printing element 1 & 3 from our HighScore array)
  
; Dimension the Highscores array with space for 5 score values
  Dim HighScores(5)
  
; print what is currently stored in cell #1 of the highscores array.
  Print HighScores(1)
  
; print what is currently stored in cell #3 of the highscores array.
  Print HighScores(3)
  
  
; show the screen and wait for a key press
  Sync
  WaitKey
  


This example will display
  
  0
  0
  



      When we run this program (cut and paste it into the PlayBASIC editor and press F5), it will successfully display the contents of cell 1 and 3 (HighScore(1) and HighScore(3)) to the screen. Both of which will be zero.

      Why ? - Well, when the array is created by the Dim command. Dim initializes all of the numeric data within the array to zero for us. So therefore, if we read the other cells (2,4,5) and displayed the contents, they'd also return zero. So we need to store something in them in order to change that.

      So lets do that.

Top







How do I store something in an array ?


      To store data in an array, we need to make an assignment to it. The assignment takes the following form.

     
MyArray(CellIndex) = ThisData


      Some care is needed on our part to ensure two things are correct!


1) We're placing the right type of data into this array. For example, we can't store String data into a Numeric (integer/Float) Arrays or vice versa. They're not compatible

2) The Cell Index that we provide, must be within the boundaries of Arrays current size. If we dimension an array to contain 10 cells, then try and access cell 15 (which would be outside of the arrays size), this will cause an error when we run our program. If this occurs, PlayBASIC will stop your program and give you what's called a runtime error. Which is a warning that something it wasn't expecting has occurred.


      When we store data in an array, the information is copied from the Right hand side of the assignment (the equals), into the array on the left. This will overwrite whatever was previously stored at that position within the array.

      So some care is needed to make sure we're storing data at the correct position. As a common programming mistake occurs when we think we're stored data at one position, when really we've made a miscalculation and it's being stored some place else. These types of errors are called logic errors and can be difficult to locate.


Example. (Assigning element 3 in our HighScore array then value 70000)

  
  HighScore(3= 70000
  



High Scores Array Contents Table
  
  ------------------------------------------------
  Cell#|    0 |    1 |    2 |     3 |    4 |    5 |
  ------------------------------------------------
  Data |    0 |    0 |    0 | 70000 |    0 |    0 |
  ------------------------------------------------
  



      Lets add this to the previous code example as see what we get.


Example. (Printing element 1 & 3 from our HighScore array)
  
; First we Dimension the Highscore array with space for 5 score values
  Dim HighScores(5)
  
; Lest store the value 70000 into cell 3 of the HighScore array
  HighScores(3= 70000
  
; print what is currently stored in cell #1
  Print HighScores(1)
  
; print what is currently stored in cell #1
  Print HighScores(3)
  
; show the screen and wait for a key press before ending
  Sync
  WaitKey
  


This example displays
  
  0
  70000
  



      This time when we run the example, we can see that we've successfully created our array, stored a piece of data in it, and have been able to display this information back to the user. So we can store data in the array and can retrieve it back.

Top






How do I read information from within an array ?


      To read the data from an array, we reverse the form we used to store data into it. So this time the array is on the Right side of the assignment(equals) symbol.

ThisData = MyArray(CellIndex)


      So it's used as part of the expression. When it's on the right hand side of the assignment (the equals symbol) we can use them data in arrays as part of a calculations , or even as a command parameter.


      Example: (This example Assigns the Variable "ThisScore" to whatever the value of element 3 is within the HighScore array)

  
  ThisScore = HighScore(3)
  



      Example: (This examples shows how we can use data within arrays as command parameters. In this case, it's using Print to display the contents of this cell within the array. But you can do this will any command)
  
  Print  HighScore(3)
  



Top






Lets put that knowledge to good use



      So that's a crash course in the very basic's of arrays, but lets put that little bit of knowledge to good use and re-create the above example, but this time using arrays, rather than variables..


  
  
; Create an Array called Highscores and make
; this array big enough for our 5 elements.
  
  Dim HighScores(5)
  
; assign each element inside the high score array a value.
  HighScores(1= 100000
  HighScores(2= 90000
  HighScores(3= 80000
  HighScores(4= 70000
  HighScores(5= 60000
  
; display the high scores to the screen
  Print HighScores(1)
  Print HighScores(2)
  Print HighScores(3)
  Print HighScores(4)
  Print HighScores(5)
  
  Sync
  WaitKey
  



High Scores Array Contents Table
  
  --------------------------------------------------
  Cell#|  0 |     1 |     2 |     3 |    4 |    5   |
  --------------------------------------------------
  Data |  0 | 100000 |90000 | 80000 | 70000 | 60000 |
  --------------------------------------------------
  


      Hmmm, by now your thinking ."jezz, that doesn't look any easier ?" and you'd be right. As what makes Arrays so convenient, is that we can now use Loops to run through and process all of the elements inside an array. So lets see if we can make it easier by using a couple of For/Next loops.


  
  
; Create an Array called Highscores and make it
;  big enough for our 5 elements.
  
  Dim HighScores(5)
  
; assign each element inside the high score array a value.
  HighestValue=100000
  
; Assign the cells in the array
  For Index = 1 To 5
     HighScores(Index) = HighestValue
     HighestValue=HighestValue - 10000
  Next Index
  
; display the high scores to the screen
  For Index=1 To 5
     Print HighScores(Index)
  Next Index
  
  Sync
  WaitKey
  
  



      This approach lets us use the same simple code to handle all of our array elements, regardless of how big the array actually is. In this example were only handling an array with 5 elements, but it could just as easily be modified to handle 10, 20, 100 ,5000 or even a million if we wanted. Which would have been totally impractical if we were to try and do that using only variables.


      Now in this last example, we'll tidy it up a bit and merge the two For/Next Loops into one. This time we'll use a variable to record the Array size.


  
  
; Create an Array called Highscores and make this array big
; enough for our 10 elements.  You can change this variable to
; modify the number of highscores you it to create & display
  
  SizeOFArray=10
  Dim HighScores(SizeOFArray)
  
; assign each element inside the high score array a value and print it.
  HighestValue=100000
  
; Start For /Next Loop
  For Index = 1 To SizeOFArray
     
   ; Store the Highest value in this position of the array
     HighScores(Index) = HighestValue
     
   ;Display this value
     Print HighScore(index)
     
   ; Subtract 10000 from highestvalue
     HighestValue=HighestValue - 10000
     
   ; continue this for/next loop until the INDEX counter reaches SIZEOFARRAY
  Next Index
  
  Sync
  WaitKey
  


Top







What else could I use arrays for ?


      Arrays are the life blood of virtually every computer program. You might use them to store anything from something as simple as a list of player names and high score tables, through to game maps and most commonly you'll be using them to store information about the characters in your games.

      As such, here's a tidbit for you dissect. This example manages a list of characters (well circles), storing the current positions of each character in a pair of arrays.

  
  
; This example controls a group of characters by storing each
; characters coordinates in a pair of arrays
  
  NumberOfObjects=10
  
; Make an array to store the X coordinate of each character
  Dim CirclesXpos(NumberOfObjects)
  
; Make an array to store the Y coordinate of each character
  Dim CirclesYpos(NumberOfObjects)
  
  
; Randomly Init each characters starting position
  For ThisCharacter=0 To NumberOfObjects
     
   ; Set this characters X position random between 0 and 800
     CirclesXpos(ThisCharacter) = Rnd(800)
     
   ; Set this characters X position random between 0 and 800
     CirclesYpos(ThisCharacter) = Rnd(600)
     
  Next
  
  
  
; Tell PB to limit this program to a max speed of
; 100 frames per second or less
  SetFPS 100
  
  
; Start of DO/LOOP
  Do
     
   ; Clear the SCreen
     Cls RGB(0,30,40)
     
     
   ; Run through and move all the game characters
     For ThisCharacter=0 To NumberOfObjects
        
      ; Get the position of this character
        xpos= CirclesXpos(ThisCharacter)
        Ypos= CirclesYpos(ThisCharacter)
        
      ; Subtract 1 from the characters X position
        Xpos=Xpos-5
        
      ; Check if the X position has left the screen edge
        If Xpos<0
         ; Reset Xpos to 800 the hand edge of the screen
           Xpos=800
           
         ; randomly reposition the Y of this character also
           Ypos=Rnd(600)
           
        EndIf
        
        
      ; Draw a circle to represent this character on screen
        Circle  Xpos,Ypos,20,true
        
      ; Store this characters new position back in the arrays
        CirclesXpos(ThisCharacter)=Xpos
        CirclesYpos(ThisCharacter)=Ypos
     Next
     
   ; draw the screen
     Sync
     
   ; loop back to the do statement, and do it all again !
  Loop
  
  



Top








Ok, Where to from here ?


      If you've come through all this unscathed, and assuming you're familiar with loops & Functions&Psub's then we recommended you experiment with the various array commands and then jump into learning about Types.

Top




 
Related Info: Functions&Psub | Loops | NamingConventions | Operators | ProgramLayout | Types | Variables :
 


(c) Copyright 2002 - 2024 - Kevin Picone - PlayBASIC.com