CSCI 201
Introduction to Algorithm Design home | homework index | labs index |
FALL 2006 |
In this lab, we will work with arrays.
An array is a data structure. It is an ordered collection of objects or primitive data elements. You access a specific element of an array by stating the collection name followed by the specific element's index number in that collection.
In Java, arrays are objects. To create an
array you create an object. The syntax for creating an array object
is slightly different from that used for other objects. To create an
array of 5 int
's called
tom
, you would type:
int[] tom = new int[5];
On the left-hand side of the assignment
operator, int[]
is the data type
array of int
and tom
is
the name of the array object. On the
right-hand side of the assignment operator, the operator
new
is being used to create an array object
containing a collection of five integer
variables.
Each element in the array has an index number associated with it. The index number of the first element is 0. Each element after that is numbered sequentially, up to the last element. This means that the index number of the last element of the array is one less than the size of the array. You can almost think of each element in an array as a variable. Because you access the "variables" of an array via an index number, there are some pretty powerful tricks you can do with arrays.
If you wanted to set 5 int
variables equal to 0, how would you do it? Perhaps like this:
june = 0; tom = 0; may = 0; scarlet = 0; apple = 0;
This is a tedious way of doing things, and you run the risk of making a mistake. To do the same task using an array, you could do the following:
int[] stuff = new int[5]; for (int i = 0; i < 5; i ++) { stuff[i] = 0; }
This is a much more efficient way of doing things. Notice that each
time the loop variable is incremented, a different element of the
array is set equal to zero. Using a for
-loop in this manner,
you can
easily perform a complex task on all of the (or specific) elements of an
array. The following Stack N' Heap demonstrates how to create and
initialize an array of integers storing the numbers from
one to five. For
simplicity, we will show the elements of the array as existing on the
stack; but, because they are contained in an object, they
are actually stored on the heap.
Code
int[] myArray = new int[5];
for (int i = 0; i < myArray.length; i ++) { myArray[i] = i + 1; } |
Stack
|
Heap
|
Temporary
|
As you see, loops and arrays are often used together. By using a loop variable as an index into an array, you can perform tasks on a large number of variables which just a few lines of code.