go to previous page   go to home page   go to next page hear noise

Answer:

The complete program is given below.


Complete Program

Notice that the two for statements are the same. This is very common. It would be nice to copy this program to a file and to run it. When you do this, change the length of the array (the 5) to some other value (say, 9) and note the effect.

Review: Recall that the scope of the identifier index declared in the for statement is limited to just the body of its loop. So in the program, there are two variables, each named index, and each limited in scope to the body of its own for.


import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array = new int[5];
    int   data;

    Scanner scan = new Scanner( System.in );

    // input the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "enter an integer: " );
      data = scan.nextInt();
      array[ index ] = data ;
    }
      
    // write out the data
    for ( int index=0; index < array.length; index++ )
    {
      System.out.println( "array[ " + index + " ] = " + array[ index ] );
    }

  }
}      

QUESTION 5:

The variable data is not really needed in this program. Mentally change the program so that this variable is not used.