3. Write a JAVA program that includes two methods named calcvaerage() and varian
ID: 3660666 • Letter: 3
Question
3. Write a JAVA program that includes two methods named calcvaerage() and variance(). The clacaverage() method should calculate and return the average of the values stored in the array named testvals. This array should be declared in the main() and should hold double type 15 values. These values are input by the user when the program is run. The variance() method should calculate and return the variance of the data stored in the testvals array. The variance is obtained by subtracting the average from each value in testvals, squaring these differences, adding them, and dividing this sum by number of elements in testvals. The values obtained from calcaverage() and variance() should be displayed using println statements within the main() function.Explanation / Answer
/*100% working code*/
public class AverageAndVariance {
static double calcvaerage(int[] testvals) {
double sum = 0.0;
for (int i = 0; i < testvals.length; i++) {
sum = sum + testvals[i];
}
return ((double) (sum / (double) (testvals.length)));
}
static double variance(int[] testvals) {
double mean = calcvaerage(testvals);
double temp;
double sum = 0.0;
for (int i = 0; i < testvals.length; i++) {
temp = testvals[i] - mean;
sum = sum + (temp * temp);
}
return ((double) (sum / (double) (testvals.length)));
}
public static void main(String[] args) {
int[] testvals = { 4, 34, 45, 343, 45, 3, 65, 56, 34, 342, 43, 67, 234,
453, 99 };
System.out.println("Average is : " + calcvaerage(testvals));
System.out.println("Variance : " + variance(testvals));
}
}
Output:-
Average is : 124.46667
Variance : 19472.38222
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.