Complete Zero

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.
go to previous page   go to home page   go to next page

Answer:

The complete program is given below.

Complete Zero

Remember to use the length of the array in testing for the end. It would be a mistake to write in a literal value like 5 because you want the method to work for all int arrays.

// 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 )
  {
    if ( elt < x.length )
      x[ elt ] = 0; 
  }

  
  // Make all the elements zero.
  void zeroAll ( int[] ar )
  {
    for ( int j=0; j < ar.length; j++ )
      ar[j] = 0;
  }

}

class ChangeTest
{
  public static void main ( String[] args )
  {
    ChangeArray cng = new ChangeArray();
    int[] value = {27, 19, 34, 5, 12} ;
    System.out.println( "Before:" );
    cng.print( value );
    
    cng.zeroAll( value  );
    System.out.println( "After:" );
    cng.print( value );
  }
}

Of course you could call your loop control variable something other than "j".

QUESTION 11:

Will the j in zeroAll() and the j in print() interfere with each other?