Programming with ActionScript 3: Flashosophy Cram Session Part III (Arrays and Loops)

Introduction:

An array is a list of items, such as variables or objects. When you want to do something more than once, use loops. Knowledge of previous tutorials is required to fully understand what is going on in this tutorial. It is crucial that you understand everything in this tutorial.

Section 1: Arrays

You use an array when you want to access or put things in a list so you can access them with ease.

Example:
//if you know how long the list is and know what values they have, define the array like this
var myGrades:Array = new Array("A", "B", "C", "D");
trace( myGrades[0] ) // 0 is the first element of the array. This outputs: A
trace( myGrades[1] ) // 1 is the 2nd element of the array. This outputs: B

// myGrades.length is the length of the array; which is 4.
// This shows the last element (4-1 =3). This is the same as myGrades[3]. This outputs: D
trace( myGrades[myGrades.length-1] )


Output:
A
B
D

The numbers inside the brackets is called an index. It is a number that points to a location of the array. An index of 0 means the beginning of the array.

//if you don't know what the inital length of the array, initialize it like this
var myGrades:Array = new Array();
myGrades.push("A"); //the push function will add the element to the bottom of the array
myGrades.push(99); //you can mix and match different variables in an array
myGrades.pop(); //the pop function removes the most recent added element to the array
myGrades.push("B");
trace(myGrades[0]); //prints first element of array
trace(myGrades[1]); //prints 2nd

Output:
A
B

Push and pop is a stack system. Think of it as stacking plates at a restaurant. Let’s say you stack 10 plates on top of one another before you start using them one by one from the top. A stack sequence is referred to as FILO (first in last out). A stack is the opposite of a queue, which is FIFO (first in first out). A queue is much like standing in line to buy lunch; being first lets you go first.

The pop function returns the value of the popped item; not just remove it from the array. This means you can assign the popped value to something else.

For example:
var numList:Array = new Array(1, 2, 3);
var money:uint = numList.pop();
money++;
trace(money); //you will get output of 4 because 3+1=4

You can also write to an array instead of just reading from it.

Example:
var numList:Array = new Array(0, 0, 0);
numList[0] = 3; //this changes the first element into 3
trace(numList); //tracing the array will output the entire array

Output:
3,0,0

Section 2: Double Arrays

Double arrays are 2 dimensional arrays. A matrix is formed when 2 dimensional arrays are formed

For example:

  C0 C1 C2
R0
0
1
2
R1
3
4
5
R2
6
7
8

If I want to get the number 4 from the matrix, I would have to say, R1,C1. Think rows and columns. Rows and columns can be inverted but you will need to be consistent in your logic and in all your accessing/writing of the double array.

When will you use double arrays? Well, any tile-based games, some puzzle games, games with any kind of coordinate systems, etc, should use them. You will also use them when you have a list of things and want to compare it with another list of things. For example, let's look at a list of home items versus its condition, where its data is a Boolean. For the sake of simplicity, here's a short example:

  Computer Bike Shoes
New
False
True
False
Used
True
False
True
Broken
False
True
True

There are other ways to define the double array matrix, but this is how I do it in AS3.

var theMatrix = new Array();
theMatrix[0] = [false,false,false];
theMatrix[1] = [true,false,true];
theMatrix[2] = [false,true,true];

trace(theMatrix[1][1]); // this returns false.

The trace statement asked for a row: Used, and column: Bike. The answer was false; the bike was not used. It is in fact new, and also broken. This means the bike was broken to begin with as soon as the person bought it from the store. How'd that happen? Who knows. Who cares?

There are 3 dimensional arrays and above. But that will get into the realm of 3D math and quantum physics; let's not touch that. This is after all, a beginner's tutorial.

Let's move on to loops so we can make use of arrays with them.

Section 3: The 'while' Loop

The while loop is very much like an 'if' statement except that the code inside the loop will be executed for as long as the condition is true.

Compile this code:

var countDown:uint = 3;
while(countDown > 0){
   countDown--; //minus 1
   trace(countDown);
}

trace("Loop complete");

Output:
2
1
0
Loop complete

In our example above, as long as countDown > 0, the code inside the loop will execute. The code inside the loop is countDown-- and a trace statement. Because countDown is being decremented every time, countDown will eventually reach 0. When the condition for the while loop is false, then the loop exists.

Make sure somewhere in the loop contains code to allow the loop to end; otherwise you will be in an infinite loop.

//doing something like this is bad for your computer's health. Flash stops this after 15 seconds for you.
while(true);

There is a loop called the 'do' loop. However I will not talk about that loop because a 'while' loop can do anything a 'do' loop does, and vice versa. I never use it so let's not waste brain cells on it.

Section 4: The 'for' Loop

The 'for' loop is good to use when you know when to stop the loop. You know exactly how many times you want it to loop. Let's say you want to run a series of code 5 times.

Compile this code:

var counter:uint = 0;
for(var i=0; i < 5; i++){
   counter++;
   trace(counter);
}

Output:
1
2
3
4
5

Let's look at the parameters of the 'for' loop. There are 3 parameters, each separated by a colon.

The first one, var i=0 makes it so that the loop counter starts at 0.

The second one, i < 5 is the condition that the loop needs to satisfy in order to repeat.

The third one, i++ increments the variable i, making the condition for the loop eventually turn from true to false (false in the loop condition is required for us to get out of the loop).

These parameters are not fixed. For example, you can have:
for(var myNum=20; myNum >= 10; myNum-=2).

You can also define the variable outside of the loop.

Example:

var myNum:int=0;
for(myNum=3; myNum > 3; myNum++)
{
trace("Inside loop: " +myNum);
}

Section 5: Using Arrays With Loops

Ok, so you've learned how arrays and loops work. But how and why would you use them? We'll, lets say I have an array of numbers that represents the number of meals I ate during the week. Then let's say I'm going on a diet and would like to eat more often but in lesser portions. Ok, I'll eat 1 more meal a day for the entire week.

The code would look like this:

//starts with 3 meals a day for weekdays and 2 on weekends (sleep in so skipped breakfast)
var mealsArr:Array = new Array(3,3,3,3,3,2,2);
for(var i=0; i<mealsArr.length; i++){ //this loop will execute 7 times
  mealsArr[i]++; //array index from 0 to 7 gets 1 added to the target value
}
trace(mealsArr); //output: 4,4,4,4,4,3,3

This really beats setting each item in the array manually doesn't it? This is especially true if you have a list of 1000 things.
mealsArr[0]++;
mealsArr[1]++;
mealsArr[2]++;
......

Let's look at a different situation. Let's say I'll eat 1 more meal each day except for Tuesdays and Thursdays because I have basketball games during lunch time.

var mealsArr:Array = new Array(3,3,3,3,3,2,2);
for(var i=0; i<mealsArr.length; i++){ //this loop will execute 7 times
   if( i == 1 || i == 3){ //if Tuesday or Thursday, minus a meal. Monday starts with index 0
    mealsArr[i]--; //minus a meal
  }
 else
    mealsArr[i]++; //add a meal in all other days
}
trace(mealsArr); //output: 4,2,4,2,4,3,3

Great, now how about the double array? To traverse a double array, you will need nested loops.

Let's use a new database.

  Marbles Ballons Crayons
New
50
20
30
Used
20
0
20
Broken
5
3
6

Now let's say you got a new shipment of items and your "New" inventory went up all by 100. Keep in mind that the "New" section is on row 0.

var myInventory = new Array();
myInventory[0] = [50,20,30];
myInventory[1] = [20,0,20];
myInventory[2] = [5,3,6];
for(var i=0; i < myInventory.length; i++){ //i is the row being traversed
  for(var j=0; j < myInventory[0].length; j++){ //j is the column being traversed
     trace(myInventory[i][j]); //this shows that the matrix is traversed from left to right, top to bottom
     if(i==0){ //if we are in column 0, which is "New" category
        myInventory[0][j]+=100; //adds to first row, all columns 100
        }
     }
}
trace(myInventory);

Output:
50
20
30
20
0
20
5
3
6
150,120,130,20,0,20,5,3,6

Take your time to decifer the code. Take your time to understand it.

Section 6: Test Yourself

If you THINK you got it, here's an exercise for you. Using the same database of marbles, balloons, and crayons, you realize that you've lost a few things. You lost 10 "used marbles", 3 "broken balloons", and 15 "new crayons".

I'll get you started:

var myInventory = new Array();
myInventory[0] = [50,20,30];
myInventory[1] = [20,0,20];
myInventory[2] = [5,3,6];
for(var i=0; i < myInventory.length; i++){
  for(var j=0; j < myInventory[0].length; j++){
     //fill in the blank here

     }
}
trace(myInventory);

When you are finished, your output should be: 50,20,15,10,0,20,5,0,6

Ending Summary

This is not a huge text book where you can neglect many details. Make sure you understand everything before moving on. Reading and doing are very different things. Learn by doing.

If you've successfully completed the exercise, you are now *=2 steps closer to graduation from your newbie status.

Published On: July 18, 2008

Next Chapter: Flashosophy Cram Session Part IV (Methods/Functions)

Previous Chapter: Flashosophy Cram Session Part II (Conditions & Operators)

 

(c) 2008 Flashosophy