next up previous
Next: Example: exhaustive search of Up: Unit 07 Previous: Expressions that denote array

Example: sum of the elements of an array of integers

We develop a static method, sumArrayValues(), that takes as parameter an array of integers, and returns the sum of the values of the array elements.

public static int sumArrayValues(int[] v) {
  int sum = 0;
  for (int i = 0; i < v.length; i++)
    sum += v[i];
  return sum;
}

Example of usage:

public static void main(String[] args) {
  // creation of an array of 100 elements
  int[] x = new int[100];

  // we assign to the element of x of index i the value 2*i
  for (int i = 0; i < x.length; i++)
    x[i] = 2*i;

  // print out the sum of the 100 array elements
  System.out.println(sumArrayValues(x));
}


next up previous
Next: Example: exhaustive search of Up: Unit 07 Previous: Expressions that denote array