Java Program To Calculate Average of Number using Array
- July 21, 2020
- by

Java Program To Calculate Average of Number using Array
In this Java Program, we calculate average of number using array.
Average is a number that is calculated by adding all the numbers together and dividing the total by the number of quantities. It is also known as mean.
E.g. Average of 5 numbers :
Average = 1 + 2 + 3 + 4 + 5 = 15 / 5 = 3
Array is a data structure consisting of collections of elements each identified by atleast one array index or key.
E.g. If you want to store 5 numbers in an array,
datatype arrayname [arraysize];
int a[5];
Logic : double[] arr = {19, 12.89, 16.5, 200, 13.7};
double total = 0;
for(int i = 0; i<arr.length; i++)
{
total = total + arr[i];
}
Step 1 : Create an array of data type double named arr and store the numbers in it.
Step 2 : Create a variable total with data type double and initialize it to 0.
Step 3 : Apply for loop, where i should be equal to zero, i should be less than the length of the array and increment i. arr.length returns the number of elements present in the array.
Step 4 : Add total and the a[i] and store it in the variable total.
Step 5 : Create a variable average and store the result of the division of total and arr.length.
Step 6 : Print the output.
Program :
public class AverageArray
{
public static void main (String[] args)
{
double[] arr = {19, 12.89, 16.5, 200, 13.7};
double total = 0;
for(int i = 0; i<arr.length; i++)
{
total = total + arr[i];
}
//arr.length returns the number of elements present in the array
double average = total / arr.length;
//This is used for displaying the formatted output
//If you give %.4f then the output would have 4 digits after decimal point
System.out.format("The average is : %.3f", average);
}
}
Output :
The average is : 52.418
For execution of the same do visit my Youtube Channel :

0 comments:
Post a Comment