Of course you remembered to initialize sum
to zero,
as below:
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.
Would the following statement be syntactically correct as part of main()
?
int avg = ArrayOps.sumElements( ar1 ) / ar1.length ;