Finding the standard deviation of all elements in an array
Hint:
double[] array = {2.5, 3.7, 4.1, 2.9, 5.2, 3.8};
sum = 0;
mean = sum / array.length;
squaredDiffSum += Math.pow(num – mean, 2);
double variance = squaredDiffSum / array.length;
double standardDeviation = Math.sqrt(variance);
Here’s a Java program that calculates the standard deviation of all elements in an array:
import java.util.Scanner; public class StandardDeviation { 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 the array double[] array = new double[size]; // Read the array elements System.out.println("Enter the elements of the array:"); for (int i = 0; i < size; i++) { System.out.print("Element " + (i + 1) + ": "); array[i] = scanner.nextDouble(); } // Calculate the mean double sum = 0; for (int i = 0; i < size; i++) { sum += array[i]; } double mean = sum / size; // Calculate the sum of squared differences double squaredDifferencesSum = 0; for (int i = 0; i < size; i++) { double difference = array[i] - mean; squaredDifferencesSum += difference * difference; } // Calculate the variance double variance = squaredDifferencesSum / size; // Calculate the standard deviation double standardDeviation = Math.sqrt(variance); // Print the result System.out.println("The standard deviation of the elements is: " + standardDeviation); } }
To use this program, you can simply copy the code into a Java file (e.g., `StandardDeviation.java`) and compile/run it using a Java compiler. The program prompts you to enter the size of the array and the elements of the array, and it then calculates and displays the standard deviation of the elements.
No comments yet! You be the first to comment.