How to Get Average of Numbers in Java


In this example we will show the method to get the average of numbers in Java.

Source Code

package com.beginner.examples;

public class GetAverage {

  public static void main(String[] args) {
    int[] nums= {11, 22, 3};
    System.out.println(avg(nums));
  }

  // The method to get the average of numbers
  public static double avg(int[] nums) {
    double total = 0;
    for (int i = 0; i < nums.length; i++) {
      total += nums[i];
    }
    double average = total / nums.length;
    return average;
  }
}

Output:

12.0
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments