Java Program To Calculate Average of the Number using Array Entered by the User.
- July 24, 2020
- by

Java Program To Calculate Average of Number using Array Entered by the User.
In this Java Program, we calculate average of number using array entered by the user.
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];
Step 1 : Import java.util.Scanner
Step 2 : Ask user how many number he want to enter by using System.out.println method.
Step 3 : Create object of Scanner class
Step 4 : Create variable n and store the entered number of the user.
Step 5 : Create an array arr and store the contents of n in it.
Step 6 : Create a variable total and initialize it to 0
Step 7 : Apply for loop, where i is equal to zero, i should be less than length of the array and increment i.
Step 8 : Print the entered element number by adding 1 in it.
Step 9 : Store value of sc.nextDouble() into array of i.
Step 10 : Close the Scanner.
Step 11 : Apply another for loop, where i is equal to zero, i should be less than length of the array and increment i.
Step 12 : Add total + array of i and store it in total.
Step 13 : Display the Result.
Program :
import java.util.Scanner;
public class AverageArray2
{
public static void main (String []args)
{
System.out.println("How many numbers you want to enter?");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
//Declaring array of n elements, the value of n is provided by the user
double[] arr = new double[n];
double total = 0;
for(int i = 0; i<arr.length; i++)
{
System.out.print("Enter Element No."+(i+1)+": ");
arr[i] = sc.nextDouble();
}
sc.close();
for(int i = 0; i<arr.length; i++)
{
total = total + arr[i];
}
double average = total / arr.length;
System.out.format("The average is : %.3f", average);
}
}
Output :
How many numbers you want to enter?
5
Enter Element No.1: 12.7
Enter Element No.2: 18.9
Enter Element No.3: 20
Enter Element No.4: 13.923
Enter Element No.5: 16.225
The average is : 16.350
For execution of the same do visit my YouTube Channel :

0 comments:
Post a Comment