Common Array Algorithms

This chapter discusses how a for loop can be used to iterate over the elements of a one-dimensional array. In addition, it also discusses enhanced for loops. The chapter demonstrates the use of arrays to solve common problems such as finding sum, average, maximum, and minimum values of numbers stored in array. Pay attention to some of the common programming errors one can make while using arrays.

3. The length of an Array


Answer:

public class CountArray
{

  public static void main ( String[] args )
  {
    int[] egArray = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };

    for ( int index= 0 ; index < 10 ; index++ )
    {
      System.out.println( egArray[ index ] );
    }
  }
}

The length of an Array

It is annoying to count the elements in an array. Worse, when you write a program you may not know in advance how many elements are needed. Array objects are created as the program runs. Often, the length of the array depends on data, and different runs of the program may process data that require different lengths of arrays.

Luckily, as it is running your program can determine how many elements an array has. The length instance variable of an array is the number of cells it has.

The for statement can be written like this:

for ( int index= 0 ; index < egArray.length; index++ )

Lines of code similar to the above are very common. Programs often use several arrays, and often "visit" each element of an array, in order.


Question 3:

Fill in the blanks below so that the elements of egArray are visited in reverse order, starting with the last element and counting down to element 0. (Copy and paste strings from anywhere on this page, if you want.)

for ( int index=  ;  ;  )

I bet that you get this question wrong!