Finding the variance of all elements in an array.
Here’s a Java program that calculates the variance of all elements in an array:
import java.util.Scanner; public class VarianceCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Read the size of the array System.out.print("Enter the size of the array: "); int size = scanner.nextInt(); // Create an array with the given size int[] arr = new int[size]; // Read the array elements System.out.println("Enter the elements of the array:"); for (int i = 0; i < size; i++) { arr[i] = scanner.nextInt(); } // Calculate the mean double sum = 0; for (int num : arr) { sum += num; } double mean = sum / size; // Calculate the variance double variance = 0; for (int num : arr) { variance += Math.pow(num - mean, 2); } variance /= size; // Print the result System.out.println("Variance: " + variance); scanner.close(); } }
In this program, we first read the size of the array from the user. Then, we create an array of the given size and read its elements. Next, we calculate the mean of the array by summing up all the elements and dividing by the size.
After that, we calculate the variance by summing up the squared differences between each element and the mean, and dividing by the size. Finally, we display the calculated variance.
You can run this program and input the array elements to find the variance of all the elements.
No comments yet! You be the first to comment.