Java array find average

Java Program – Calculate Average of Numbers

To calculate the average of numbers in an array or arraylist, use a loop statement to find the sum of all the numbers in the array, and divide the sum with number of elements.

In this tutorial, we write Java programs to compute average of numbers in an array and ArrayList.

Example 1 – Average of Numbers in Array

In this example, we shall use Java While Loop, to compute the average.

Algorithm

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an array with number, of whom you would like to find average.
  3. Initialize sum = 0;
  4. Initialize i = 0;
  5. Check if i is less than number of elements in array. If not go to step 8.
  6. Add sum with number in array at index i, and store in the sum itself.
  7. Increment i. Go to step 5.
  8. Compute average = sum / number of elements in array.
  9. Stop.

Java Program

/** * Java Program - Average of Numbers */ public class Average < public static void main(String[] args) < //numbers int[] nums = ; float sum = 0; //compute sum int i=0; while(i < nums.length) < sum += nums[i]; i++; >//compute average float average = (sum / nums.length); System.out.println("Average : "+average); > >

Note: We are using float datatype for sum variable to save the precision after computing average. If you use int datatype for sum , when dividing it with number of elements, we lose the decimal part of the average.

Example 2 – Average of Numbers in Array

In this example, we shall use Java Advanced For Loop, to compute the average.

Algorithm

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an array with numbers, of whom you would like to find average.
  3. Initialize sum = 0;
  4. For each number in the array, add the number to sum.
  5. Compute average = sum / number of elements in array.
  6. Stop.

Java Program

/** * Java Program - Average of Numbers */ public class Average < public static void main(String[] args) < //numbers int[] nums = ; float sum = 0; //compute sum for(int num:nums) sum += num; //compute average float average = (sum / nums.length); System.out.println("Average : "+average); > >

Example 3 – Average of Numbers in ArrayList

In this example, we shall use Java Advanced For Loop, to compute the average.

Algorithm

We shall use the following algorithm to find the average of numbers.

  1. Start.
  2. Read array of numbers. Or initialize an ArrayList with numbers, of whom you would like to find average.
  3. Initialize sum = 0;
  4. For each number in the ArrayList, add the number to sum.
  5. Compute average = sum / number of elements in array.
  6. Stop.
Читайте также:  Java home environment variable jdk or jre

Java Program

import java.util.ArrayList; /** * Java Program - Average of Numbers */ public class Average < public static void main(String[] args) < //numbers ArrayListnums = new ArrayList(); nums.add(10); nums.add(13); float sum = 0; //compute sum for(int num:nums) < sum += num; >//compute average float average = (sum / nums.size()); System.out.println("Average : "+average); > >

Conclusion

In this Java Tutorial, we learned how to find the average of numbers in an array or a ArrayList, using looping statements.

Источник

Java Array Average

Array Average – To find the average of numbers in a Java Array, use a looping technique to traverse through the elements, find the sum of all elements, and divide with number of elements in the array.

In this tutorial, we will learn how to find the average of elements in array, using different looping statements.

Java Integer Array Average using While Loop

In the following program, we will initialize an integer array, and find the average of its elements using Java While Loop.

Java Program

/** * Java Program - Average of Numbers */ public class ArrayAverage < public static void main(String[] args) < int numbers[] = ; float sum = 0; int index = 0; while (index < numbers.length) < sum += numbers[index]; index++; >float average = sum/numbers.length; System.out.println("Average : " + average); > >

Java Float Array Average using For Loop

In the following program, we will initialize a float array, and find the average of its elements using Java For Loop.

Java Program

/** * Java Program - Average of Numbers */ public class ArrayAverage < public static void main(String[] args) < float numbers[] = ; float sum = 0; for (int index = 0; index < numbers.length; index++) < sum += numbers[index]; >float average = sum/numbers.length; System.out.println("Average : " + average); > >

Java Double Array Average using For-each Loop

In the following program, we will initialize a double array, and find the average of its elements using Java For-each Loop.

Java Program

/** * Java Program - Average of Numbers */ public class ArrayAverage < public static void main(String[] args) < double numbers[] = ; double sum = 0; for (double number: numbers) < sum += number; >double average = sum/numbers.length; System.out.println("Average : " + average); > >
Average : 1.0444444444444443

Conclusion

Concluding this Java Tutorial, we learned how to find Average of a Java Array with some of the combinations of numeric datatypes for array elements and looping technique. You may use any looping technique on any of the numeric datatypes and find the Java Array average.

Источник

Java Program to Calculate average using Array

We will see two programs to find the average of numbers using array. First Program finds the average of specified array elements. The second programs takes the value of n (number of elements) and the numbers provided by user and finds the average of them using array.

To understand these programs you should have the knowledge of following Java Programming concepts:
1) Java Arrays
2) For loop

Example 1: Program to find the average of numbers using array

public class JavaExample < public static void main(String[] args) < double[] arr = ; double total = 0; for(int i=0; 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); > >

Example 2: Calculate average of numbers entered by user

In this example, we are using Scanner to get the value of n and all the numbers from user.

import java.util.Scanner; public class JavaExample < public static void main(String[] args) < System.out.println("How many numbers you want to enter?"); Scanner scanner = new Scanner(System.in); int n = scanner.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; iscanner.close(); for(int i=0; i double average = total / arr.length; System.out.format("The average is: %.3f", average); > >
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: 15.6 The average is: 16.225

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

Читайте также:  Input text события javascript

Calculate Sum and Average of Array Items

Learn to find the sum and average of the numbers stored in an array. We will be using the Java Stream API and simple for loop to find these values.

Note that the numbers in Java are represented with 8 primitives i.e. short, char, byte, boolean, int, float, long and double.

  • We can use IntStream for short, char, byte, boolean and int values.
  • We can use LongStream for long values.
  • We use DoubleStream for floating point numbers such as float and double.

When we pass the primitive arrays in the Arrays.stream() method then we get any one type of the stream i.e. IntStream , LongStream or DoubleStream .

The above information is necessary while getting the stream from an array, and using appropriate methods for calculating the aggregate values such as sum and average.

1. Finding Sum of Array Items

There are a couple of ways to get the sum of numbers stored in an array.

  • long Stream.sum()
  • long Stream.summaryStatistics().sum()
  • Iterating items using for loop.

Let us see the example of both methods using int[] and Integer[] array types. We will get the sum in either long or double data type based on the type of stream we are getting the array.

int[] intArray = ; Integer[] integerArray = ; //1 long sum = Arrays.stream(intArray).sum(); //2 long sum = Arrays.stream(integerArray).mapToInt(i -> i).sum(); //3 long sum = Arrays.stream(intArray).summaryStatistics().getSum();

If we want to loop the item, it can be done as follows.

long sum = 0; for (int value : intArray) < sum += value; >System.out.println(sum);

2. Finding Average of Array Items

Finding the average is pretty much similar to finding the sum as described in the previous section. We can call the stream.average() method in place of sum() .

The data type used for storing the average is double.

//1 double average = Arrays.stream(intArray).average().orElse(Double.NaN); //2 double average = Arrays.stream(intArray).summaryStatistics().getAverage();

In this short tutorial, we learned to use the stream API to get the sum and the average of the items stored in an array. Using the streams provides additional benefits, such as applying the filtering on the stream items without affecting the original array.

Источник

Java Program to Calculate Average Using Arrays

Twitter Facebook Google Pinterest

A quick and practical guide to find and to calculate the average of numbers in array using java language.

1. Overview

In this article, you’ll learn how to calculate the average of numbers using arrays.

You should know the basic concepts of a java programming language such as Arrays and forEach loops.

We’ll see the two programs on this. The first one is to iterate the arrays using for each loop and find the average.

Читайте также:  Entering spaces in html

In the second approach, you will read array values from the user.

Let us jump into the example programs.

Java Program to Calculate Average Using Arrays

2. Example 1 to calculate the average using arrays

First, create an array with values and run. the for loop to find the sum of all the elements of the array.

Finally, divide the sum with the length of the array to get the average of numbers.

package com.javaprogramto.programs.arrays.average; public class ArrayAverage < public static void main(String[] args) < // create an array int[] array = < 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 >; // getting array length int length = array.length; // default sium value. int sum = 0; // sum of all values in array using for loop for (int i = 0; i < array.length; i++) < sum += array[i]; >double average = sum / length; System.out.println("Average of array : "+average); > >

3. Example 2 to find the average from user inputted numbers

Next, let us read the input array numbers from the user using the Scanner class.

import java.util.Scanner; public class ArrayAverageUserInput < public static void main(String[] args) < // reading the array size. Scanner s = new Scanner(System.in); System.out.println("Enter array size: "); int size = s.nextInt(); // create an array int[] array = new int[size]; // reading values from user keyboard System.out.println("Enter array values : "); for (int i = 0; i < size; i++) < int value = s.nextInt(); array[i] = value; >// getting array length int length = array.length; // default sium value. int sum = 0; // sum of all values in array using for loop for (int i = 0; i < array.length; i++) < sum += array[i]; >double average = sum / length; System.out.println("Average of array : " + average); > >
Enter array size: 5 Enter array values : 12 23 34 45 56 Average of array : 34.0

4. Conclusion

In this article, you’ve seen how to calculate the average number in an array.

All examples shown are in GitHub.

Labels:

SHARE:

Twitter Facebook Google Pinterest

About Us

Java 8 Tutorial

  • Java 8 New Features
  • Java 8 Examples Programs Before and After Lambda
  • Java 8 Lambda Expressions (Complete Guide)
  • Java 8 Lambda Expressions Rules and Examples
  • Java 8 Accessing Variables from Lambda Expressions
  • Java 8 Method References
  • Java 8 Functional Interfaces
  • Java 8 — Base64
  • Java 8 Default and Static Methods In Interfaces
  • Java 8 Optional
  • Java 8 New Date Time API
  • Java 8 — Nashorn JavaScript

Java Threads Tutorial

Kotlin Conversions

Kotlin Programs

Java Conversions

  • Java 8 List To Map
  • Java 8 String To Date
  • Java 8 Array To List
  • Java 8 List To Array
  • Java 8 Any Primitive To String
  • Java 8 Iterable To Stream
  • Java 8 Stream To IntStream
  • String To Lowercase
  • InputStream To File
  • Primitive Array To List
  • Int To String Conversion
  • String To ArrayList

Java String API

  • charAt()
  • chars() — Java 9
  • codePointAt()
  • codePointCount()
  • codePoints() — Java 9
  • compareTo()
  • compareToIgnoreCase
  • concat()
  • contains()
  • contentEquals()
  • copyValueOf()
  • describeConstable() — Java 12
  • endsWith()
  • equals()
  • equalsIgnoreCase()
  • format()
  • getBytes()
  • getChars()
  • hashcode()
  • indent() — Java 12
  • indexOf()
  • intern()
  • isBlank() — java 11
  • isEmpty()
  • join()
  • lastIndexOf()
  • length()
  • lines()
  • matches()
  • offsetByCodePoints()
  • regionMatches()
  • repeat()
  • replaceFirst()
  • replace()
  • replaceAll()
  • resolveConstantDesc()
  • split()
  • strip(), stripLeading(), stripTrailing()
  • substring()
  • toCharArray()
  • toLowerCase()
  • transform() — Java 12
  • valueOf()

Spring Boot

$show=Java%20Programs

$show=Kotlin

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,

A quick and practical guide to find and to calculate the average of numbers in array using java language.

Источник

Оцените статью