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 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 ) { ArrayOps operate = new ArrayOps(); int[] ar1 = { -20, 19, 1, 5, -1, 27, 19, 5 } ; System.out.println("The sum of elements is: " + operate.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 correct as part of main()
?
int value = operate.sumElements( ar1 ) / 4 + 32;