go to previous page   go to home page   go to next page
cng.zeroElt( value, 4 );

Answer:

The element in cell 4 of the array would be set to zero.

Step-by-step Explanation

Here is the program again, with a step-by-step explanation of how it works. If this is already clear to you, skip this page.

The program: Description of the action:
// Array Example
//
class ChangeArray
{
  void print ( int[] x )
  {
    for ( int j=0; j < x.length; j++ )
      System.out.print( x[j] + " " );
    System.out.println( );
  }

  void zeroElt ( int[] x, int elt )         // 6.
  {
    if ( elt < x.length )                   // 7.
      x[ elt ] = 0;                         // 8.
  }
}

class ChangeTest
{
  public static void main ( String[] args ) // 1.
  {
    ChangeArray cng = new ChangeArray();    // 2.
    int[] value = {27, 19, 34, 5, 12} ;     // 3.
    System.out.println( "Before:" );        // 4.
    cng.print( value );
    
    cng.zeroElt( value, 0 );                // 5.
    System.out.println( "After:" );         // 9.
    cng.print( value );
  }
}
  1. The program starts running with the static main method.
  2. A ChangeArray object is constructed.
  3. The int[] object value is constructed and initialized.
  4. The numbers held in value are printed out.
    • Before: 27 19 34 5 12 is printed
  5. The zeroElt() method is called with value and 0 as parameters.
  6. A reference to the array value is copied into the parameter x, and 0 is copied into the parameter elt.
  7. The zeroElt() method checks if the requested element 0 exists
  8. Element 0 of the array is set to zero.
  9. The numbers now held in value are printed out.
    • After: 0 19 34 5 12 is printed

QUESTION 9:

Could ChangeArray have a method that changes several elements of an array?