In: Computer Science
This is JAVA
Return the centered average of an array of ints, which we'll say is the mean average of the values, except ignoring the largest and smallest values in the array. If there are multiple copies of the smallest value, ignore just one copy, and likewise for the largest value. Use int division to produce the final average. You may assume that the array has a length of 3 or more.
1
public int centeredAverage(int[] nums)
2
{
3
4
}
public int centeredAverage(int[] nums)
{
int min,max,sum=0;
min=nums[0];
max=nums[0];
for(int i=0;i<nums.length;i++)
{
if(max<nums[i])
max=nums[i];
if(min>nums[i])
min=nums[i];
sum+=nums[i];
}
int avg=(sum-max-min)/(nums.length-2);
return avg;
}
Complete program:-
import java.util.Scanner;
public class MyClass {
public static int centeredAverage(int[] nums)
{
int min,max,sum=0;
min=nums[0];
max=nums[0];
for(int i=0;i<nums.length;i++)
{
if(max<nums[i])
max=nums[i];
if(min>nums[i])
min=nums[i];
sum+=nums[i];
}
int avg=(sum-max-min)/(nums.length-2);
return avg;
}
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the array size : ");
int size=sc.nextInt();
int []arr=new int[size];
System.out.println("Enter the array elements : ");
for(int i=0;i<size;i++)
arr[i]=sc.nextInt();
int avg=centeredAverage(arr);
System.out.println("Average : "+avg);
}
}