JAVA   138

Compute Sum and Average of Array Elements

Guest on 23rd September 2021 05:42:30 PM

  1. class Main {
  2.  public static void main(String[] args) {
  3.  
  4.    int[] numbers = {4, -7, 0, 3, 14, -23, 26, 7, 6, 10};
  5.    int sum = 0;
  6.    Double average;
  7.    
  8.    // access all elements using for each loop
  9.    // add each element in sum
  10.    for (int number: numbers) {
  11.      sum += number;
  12.    }
  13.  
  14.    // get the total number of elements
  15.    int arrayLength = numbers.length;
  16.  
  17.    // calculate the average
  18.    // convert the average from int to double
  19.    average =  ((double)sum / (double)arrayLength);
  20.  
  21.    System.out.println("Sum = " + sum);
  22.    System.out.println("Average = " + average);
  23.  }
  24. }

Raw Paste


Login or Register to edit or fork this paste. It's free.