go to previous page   go to home page   go to next page

Answer:

Of course you remembered to initialize sum to zero, as below:


Complete Sum Method

class ArrayOps
{
  // previous methods go here 

  // add up all the elements in an array
  public static int sumElements ( int[] nums )
  {
    int sum = 0;

    for ( int j=0; j < nums.length; j++  )
      sum += nums[j];

    return  sum;
  }

}

class ArrayDemo
{
  public static void main ( String[] args ) 
  {
    int[] ar1 =  { -20, 19, 1, 5, -1, 27, 19, 5 } ;
 
    System.out.println("The sum of elements is: " + ArrayOps.sumElements( ar1 ) );   
  }

}

Here is a complete program that includes the new method. All the previous methods of the class can be included where the comment indicates.


QUESTION 17:

Would the following statement be syntactically correct as part of main()?

int avg =   ArrayOps.sumElements( ar1 ) / ar1.length ;   

go to previous page   go to home page   go to next page