Java program to calculate standard deviation

‮sptth‬://www.theitroad.com

To calculate the standard deviation in Java, you can use the following program:

import java.util.Scanner;

public class StandardDeviation {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the number of elements: ");
        int n = input.nextInt();

        double[] numbers = new double[n];
        double sum = 0;

        System.out.print("Enter the elements: ");
        for (int i = 0; i < n; i++) {
            numbers[i] = input.nextDouble();
            sum += numbers[i];
        }

        double mean = sum / n;
        double deviation = 0;

        for (int i = 0; i < n; i++) {
            deviation += Math.pow(numbers[i] - mean, 2);
        }

        double standardDeviation = Math.sqrt(deviation / n);

        System.out.println("The standard deviation is " + standardDeviation);
    }
}

In this program, we first take input from the user for the number of elements and the elements themselves. Then, we calculate the mean and deviation using the formula:

deviation = (x1 - mean)^2 + (x2 - mean)^2 + ... + (xn - mean)^2
mean = (x1 + x2 + ... + xn) / n

Finally, we calculate the standard deviation by taking the square root of the deviation divided by the number of elements. The Math.pow() and Math.sqrt() methods are used for the calculation of the deviation and standard deviation, respectively.