Here is a java program to find average of all array elements. Given an array of integers of size N, we have to find the average of all array elements.
Input Array 3 5 3 8 1 Average = 4
Algorithm to find average of all array elements
Let inputArray is an integer array having N elements.
Let inputArray is an integer array having N elements.
- Declare an integer variable 'sum' and initialize it to 0. We will use 'sum' variable to store total sum of elements of array.
- Using for loop, we will traverse inputArray from array from index 0 to N-1.
- For any index i (0<= i <= N-1), add the value of element at index i to sum.
sum = sum + inputArray[i]; - After termination of for loop, sum will contain the total sum of all array elements.
- Now calculate average as : Average = sum/N;
Java program to find average of all array elements.
package com.tcc.java.programs; import java.util.*; public class ArrayElementsAverage { public static void main(String args[]) { int count, sum = 0, i; int[] inputArray = new int[500]; Scanner in = new Scanner(System.in); System.out.println("Enter number of elements"); count = in.nextInt(); System.out.println("Enter " + count + " elements"); for(i = 0; i < count; i++) { inputArray[i] = in.nextInt(); sum = sum + inputArray[i]; } System.out.println("Average : " + (double)sum/count); } }Output
Enter number of elements 5 Enter 5 elements 5 5 5 5 5 Average : 5.0
Enter number of elements 6 Enter 6 elements 1 2 3 4 5 6 Average : 3.5
Recommended Posts