Java - Stepping through Arrays [Digg.com This!]
Let's say we have an array as follows:
int[] myintarray = new int[10];
~~~
To step through the array one item at a time we can do:
for (int i=0;i< myintarray.length; i++)
{
}
~~~
To get the item at position i, we do:
myintarray[i]
~~~
So if we want to print out each item in our array, we do:
for (int i=0; i<myintarray.length; i++)
{
System.out.println("Num as position " + i + " is " + myintarray[i]);
}
Things to note:
1. The for loops above step FORWARD through the array, going from item 0, to 1, then 2, 3, etc, up to the length of the array.
2. myintarray.length does NOT have () after length. This is because length is NOT a method.
~~~
To step backwards through the array using a similar for loop, we can do:
for (int i=myintarray.length-1; i>=0; i--)
{
System.out.println("Num as position " + i + " is " + myintarray[i]);
}
This would go from item 9, to 8, then 7, 6, etc, to 0.


