Program to Calculate the Mean & Standard deviation
Program Description
Write a java program to calculate the mean and standard deviation of the given population of numbers.
IPO Chart
Input
We will take input from the user for the population of numbers.
Process
mean = (x1 + x2 +… xn)/n
sd = sqrt( ((x1- mean)^2 + (x2- mean)^2 +…+ (xn- mean)^2 )/n)
Output
The program will output the mean and standard deviation.
Environment & Tools Used
The tools and environment used in the example are as follows:
- JDK
- Eclipse IDE
- Windows 10 Operating System
Java Program
Launch the Eclipse IDE. Create a new class for the program. Add the program code.
The program uses Scanner class to take input from the user.
import java.util.Scanner; public class StandardDeviation { public static final int ARRAYSIZE=4; public static void main (String [] args) { System.out.println("Enter numbers to find Standard Deviation"); Scanner input = new Scanner(System.in); double[] arr= new double[ARRAYSIZE]; double sum=0.0, mean=0.0,sumOfSquares=0.0,meanOfSquares=0.0; for (int i=0; i<ARRAYSIZE; i++) //Take input in the array { System.out.println("Enter a number : "); arr[i]=input.nextDouble(); sum+=arr[i]; //sum of all elements } mean=sum/ARRAYSIZE; System.out.println("Mean of elements := "+mean);
//Display mean of all elements double[] sd= new double[ARRAYSIZE]; for (int i=0; i<ARRAYSIZE; i++) //calculate standard deviation { sd[i]=Math.pow((arr[i]-mean),2); sumOfSquares+=sd[i]; } meanOfSquares=sumOfSquares/(ARRAYSIZE); double deviation=Math.sqrt(meanOfSquares); System.out.println("Standard Deviation := "+ deviation); } }
Program Output
Save the program in the Eclipse IDE and run the application. Right-click in the code editor and choose Run As >> Java Application to run the program.
Enter numbers to find Standard Deviation
Enter a number : 7
Enter a number : 4
Enter a number : 5
Enter a number : 2
Mean of elements := 4.5
Standard Deviation := 1.8027756377319946
Screenshot
—
Java Tutorial on this website:
https://www.testingdocs.com/java-tutorial/
More information on Java can be found on the official website: