Search code examples
javaarraysaverage

Save array result from a for loop to a variable


I have an assignment where I am supposed to have 6 elements in an integer array and program supposed to find the highest and lowest element in an array and omit those two elements and find the average for the remaining four elements. So far my program is able to find the lowest and highest number in that array and able to omit it, however, I cant seem to save those results from the loop to a variable so I can start to calculate my average. the code is

int bucky[] = { 4, 6, 8, 19, 199, 400 };
int hello = 0;
int max = 0;

for (int i = 0; i < bucky.length; i++) {
    if (bucky[i] > max) {
        max = bucky[i];
    }
}
System.out.println("Max number is " + max);

int min = 0;
int j = 1;
for (int i = 0; i < bucky.length; i++) {
    if (bucky[i] < bucky[j]) {
        min = bucky[i];
        j = i;
    }
}
System.out.println("min number is " + min);

System.out.print("{");
for (int i = 0; i < bucky.length; i++) {
    if (bucky[i] != max) {
        if (bucky[i] != min) {
            System.out.print(" " + bucky[i]);
        }
    }
}
System.out.print("}");

So far it prints out {6 8 19 199}. I want to be able to save them in a variable and calculate the average. Any help would be appreciated.


Solution

  • Here is a simple program that might achieve what you are after.

    What should happen if all elements have the same value?

    int[] input = {0,1,2,3,4,5};
    
    int max = input[0];
    int min = input[0];
    int sum = 0;
    
    for(int i : input){
        sum += i;
        if(i < min){
            min = i;
        }else if(i > max){
            max = i;
        }
    }
    
    System.out.println("sum for input is : " + sum);
    System.out.println("highest value element is : " + max);
    System.out.println("lowest value element is : " + min);
    System.out.println("sum excluding extreme elements is : " + (sum - min -max));
    
    // have cast the result as a float as i dont know if average should be truncated or not
    System.out.println("average excluding extreme elements is : " + ((float)(sum - min -max)/(input.length-2)));