How to Average a Set of Numbers in Java


The example aims to calculate the average of a set of numbers in Java.

Source Code

package com.beginner.examples;

public class CalculateAverageValueExample {

	public static void main(String[] args) {

		int[] nums1= { 1, 3, 5, 6 };
		int[] nums2 = { 2, 3, 6, 1 };

		System.out.println("nums1---Avg:"+avg(nums1));
		System.out.println("nums2---Avg:"+avg(nums2));

	}

	// The method of calculating the average value
	public static double avg(int[] nums) {

		// Use double to store the sum
		double sum = 0;

		// cumulative
		for (int i = 0; i < nums.length; i++) {
			sum += nums[i];
		}

		// In order not to lose data, use a double to store the average
		double avg = sum / nums.length;

		return avg;
	}

}

Output:

nums1---Avg:3.75
nums2---Avg:3.0
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments