Variance of an Array in Java
The
variance of an array indicates the degree to which
the numbers of the array vary from its mean value. Variance tells how values are spread out. Get
an array of Integers arr[] with size n and calculate the variance of arr[].The Output should be printed in
two decimal places.
Example
Input 1:
4
5 6 7 8
Output 1:
1.66
Explanation:
(Variance
is average of squared difference between the numbers and mean value)
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 Variance
{
public static void main(String args[])
{
//Variable and Object Declarations
Scanner input = new Scanner(System.in);
int n;
float sum = 0f;
float mean, variance;
//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);
System.out.printf("%.2f", variance);
}
}