To compute the sum and average of the elements of an array in Java, you can use a for
loop to iterate through the array and keep track of the sum and count of the elements. Then, you can divide the sum by the count to calculate the average.
Here is an example of how you can compute the sum and average of an array of integers in Java:
int[] numbers = {1, 2, 3, 4, 5}; int sum = 0; int count = 0; for (int number : numbers) { sum += number; count++; } double average = (double) sum / count; System.out.println("Sum: " + sum); System.out.println("Average: " + average);Source:www.lautturi.com
In this example, we iterate through the array numbers
and keep track of the sum and count of the elements. Then, we divide the sum by the count to calculate the average. The sum and average are printed to the console.
You can also use the IntStream
class and its sum
and average
methods to compute the sum and average of an array of integers. Here is an example of how to do this:
int[] numbers = {1, 2, 3, 4, 5}; int sum = Arrays.stream(numbers).sum(); double average = Arrays.stream(numbers).average().getAsDouble(); System.out.println("Sum: " + sum); System.out.println("Average: " + average);
This example uses the IntStream
class to create a stream of integers from the array numbers
, and then uses the sum
and average
methods to compute the sum and average of the elements in the stream.