Answer:

stuff[0] has 23
stuff[1] has 38
stuff[2] has 14
stuff[3] has 0
stuff[4] has 0

Using a Variable as an Index

The index of an array is always an integer type. It does not have to be a literal. It can be any expression that evaluates to an integer. For example, the following are legal:

int values[] = new int[7];
int index;

index  = 0;
values[ index ] = 71;       // put 71 into cell 0

index  = 5;
values[ index ] = 23;       // put 23 into cell 5

index  = 3;
values[ 2+2 ] = values[ index-3 ];  // same as values[ 4 ] = values[ 0 ];

Using an expression for an array index is a very powerful tool. Often a problem is solved by organizing the data into arrays, and then processing that data in a systematic way using variables as indexes. Here is a further example:

class arrayEg2
{
  public static void main ( String[] args )
  {
    double[] val = new double[4];  //an array of double 

    val[0] = 0.12;
    val[1] = 1.43;
    val[2] = 2.98;

    int j = 3;
    System.out.println( "cell 3: " + val[ j   ] );
    System.out.println( "cell 2: " + val[ j-1 ] );

    j = j-2;
    System.out.println( "cell 1: " + val[ j   ] );
   }
}

You can, of course, copy this program to your editor, save it and run it. Arrays can get confusing. Playing around with a simple program now will pay off later.

QUESTION 8:

What does the above program output?

cell 3:
cell 2:
cell 1: