Complete Sum Method

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:

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

Complete Sum Method

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.

QUESTION 16:

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

int value =   operate.sumElements( ar1 ) / 4 + 32;