The average of the numbers can be calculated as the sum of all numbers divided by the number of elements.
In the question, it is mentioned that the program should find an average of 4 numbers in one place whereas in the third line it is written to find an average of 6 numbers.
I have taken an array of 6 elements to store values and a variable to store the average value of the 6 numbers.
The program outputs the average values as a floating-point number.
If you want to find the average of 4 elements you can change the array size to 4 and for loop to run for 4 times.
Code:-
package average;
import java.util.Scanner; //Scanner class
public class Average {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in); //Scanner class object to take input
double arr[] = new double[6]; //array of double variables to store value
double average = 0; //variable to store average value
for(int i=0;i<6;i++){ //loop to take input
arr[i] = sc.nextDouble(); // taking input
}
for(int i=0;i<6;i++){ // loop to calculate sum
average = average + arr[i]; //calculating sum of 6 variables
}
average /= 6; //dividing by 6 to get average
System.out.println(average); // printing the result
}
}
Output:-
The code is well commented and user-friendly.
Get Answers For Free
Most questions answered within 1 hours.