The program shows how to Calculate the Average in an Array element in java. The program uses a scanner class to take the input from the user. It takes the size of an array and the array elements and adds those elements and displays them accordingly.
If you do not know the working process of for loop then click the link below.
Java Program to Calculate Average of Elements in an Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | //calculate the average in an array element using for loop import java.util.Scanner; public class AverageForLoop { public static void main(String args[]) { int num, sum = 0; float average; Scanner s = new Scanner(System.in); System.out.print("Enter the number of elements for an array: "); num = s.nextInt(); int a[] = new int[num]; System.out.println("Enter elements of array:"); for(int i = 0; i < num; i++) { a[i] = s.nextInt(); } for(int i=0; i < a.length ; i++) sum = sum + a[i]; //calculate average value average = sum / num; System.out.println("Average value of array elements is : " +average); } } |
Output:
Enter the number of elements for an array: 5
Enter elements of array:
1
2
3
4
5
Average value of array elements is : 3.0