Of course you remembered to initialize sum to zero,
as below:
Here is a complete program that includes the new method. All the previous methods of the class can be included where the comment indicates.
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 ) );
}
}
Notice how the main() method uses the method call
as if it were a number:
System.out.println("The sum of elements is: " +
operate.sumElements( ar1 ) );
--------------------------
55
The method call returns the value 55 (the sum of all the array elements). That value can be used just as if it had been written there as a constant.
Would the following statement be correct as part of main()?
int value = operate.sumElements( ar1 ) / 4 + 32;