[Solved] I want to find the average in a given array, and find the closest number to that average in java

[ad_1]

To find the average in the given array and find the number which is closest to the average,

public static void main(String[] args)
{
    int array[] = new int[]
    { 1, 2, 3, 4, 5, 6, 7, 8 };
    int sum=0;

    double avg;
    for (int i = 0; i < array.length; i++)
    {
        sum += array[i];
    }
    avg = sum / array.length;
    System.out.println(avg);
    
    double difference = Math.abs(array[1] - avg);
    Integer closest = array[1];
    for (int i = 0; i < array.length; i++)
    {
        double diff = Math.abs(array[i] - avg);
        if(difference > diff)
        {
            difference = diff;
            closest = array[i];
        }
    }
    System.out.println(closest);
}

0

[ad_2]

solved I want to find the average in a given array, and find the closest number to that average in java