Saturday, February 18, 2006

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.

1 Comments:

At 4:47 AM, winson said...

helow.... how can you get the lenght of the string... example..
Enter string: ward
output: 4...
because the i enter a word.. then the program will count the letter... and output the number of letter entered.

 

Post a Comment

<< Home