How to find average of one dimensional array elements ?
The blog provides the technical approach on ” How to find average of one dimensional array elements ?”
Problem Statement:
Java program to find average of one dimensional array elements ?
Solution Approach:
- Get the Array Count as User Input
- Get the Array Elements as User Input
- Iterate the Array Elements
- Get the sum of all array elements
- Divide the array element sum by total number of elements
package com.java.planforexams.array;
import java.util.Scanner;
public class ArrayElementAverage {
public static void main(String[] args) {
// Scanner object for reading User Input
Scanner scan = new Scanner(System.in);
int count,arrayElemntSum = 0;
float arrayElementAverage;
// Receive the Array Element Count from User
System.out.print("Provide the Array Element Count : ");
// Get the Array Count
count = scan.nextInt();
//Set the Array Size with Count value
int arrayInputFromUser[] = new int[count];
// Receive the Array Elements from User.
System.out.println("Enter the elements:");
// Iterate the array elements
for (int incr=0; incr<count; incr++)
{
arrayInputFromUser[incr] = scan.nextInt();
arrayElemntSum = arrayElemntSum + arrayInputFromUser[incr];
}
arrayElementAverage = (float)arrayElemntSum / count;
System.out.print("Average of the array elements is : " +arrayElementAverage);
}
}
Output:
Provide the Array Element Count : 6
Enter the elements:
2
12
43
56
7
8
Average of the array elements is : 21.333334
Leave a Reply