Standard Deviation of an Array in Java
The square
root of variance is the standard deviation. It is a gauge of how far data
deviates from the mean. Get an array of Integers arr[] with size n and calculate
the standard deviation of arr[].The
Output should be printed in two decimal places.
Example
Input 1:
4
5 6 7 8
Output 1:
1.12
Explanation:
(Standard
Deviation is the Square root of Variance)
Try your Solution
Strongly recommended to Solve it on your own, Don't directly go to the solution given below.
Program or Solution
import java.util.*;
class Sd
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n;
float sum = 0f;
double mean, variance, sd;
//Getting size of Array & Declare Array arr[]
n = input.nextInt();
int arr[] = new int[n];
//Get n values to array arr[]
for(int i = 0; i<n; i++)
{
arr[i] = input.nextInt();
}
//Calcualte Sum and Mean
for(int i = 0; i<n; i++)
{
sum+= arr[i];
}
mean = sum/n;
//Calculate Variance for Whole Population
sum=0;
for(int i = 0; i<n; i++)
{
double diff = arr[i]-mean;
sum += Math.pow(diff,2);
}
variance = sum/(n);
sd = Math.sqrt(variance);
System.out.printf("%.2f", sd);
}
}