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.

6. Run-time Array Length


Answer:

The two lines:

      data  = scan.nextInt();
      array[ index ] = data ;

can be replaced by the single line:

       array[ index ] = scan.nextInt();

And then the declaration int data; should be removed.

Run-time Array Length

An array object is constructed as the program runs (as are all objects). When an array is constructed, its size can be in a variable.

Here is the previous example, with some modifications:

import java.util.Scanner ;

class InputArray
{

  public static void main ( String[] args )
  {

    int[] array;
    int   data;
    Scanner scan = new Scanner( System.in );

    // determine the size and construct the array
    System.out.print( "What length is the array? " );
    int size = scan.nextInt();

    array  = new int[  ]; 

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

  }
} 

Question 6:

Fill in the blank.