Golang Tutorials - Learn Go Programming with Easy Step-by-Step Guides

Explore comprehensive Golang tutorials for beginners and advanced programmers. Learn Go programming with easy-to-follow, step-by-step guides, examples, and practical tips to master Go language quickly.

Find Array Average in Java

Find Array Average in Java

Alright! Here's how you can find the average of an array in Java:


Java Program to Find the Average of Array Elements

import java.util.Scanner;public class ArrayAverage {    public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        System.out.print("Enter the number of elements: ");        int n = scanner.nextInt();  // Size of array        int[] numbers = new int[n];        int sum = 0;        System.out.println("Enter " + n + " numbers:");        // Input array elements        for (int i = 0; i < n; i++) {            numbers[i] = scanner.nextInt();            sum += numbers[i];  // Add to sum        }        // Calculate average        double average = (double) sum / n;        System.out.println("Average = " + average);        scanner.close();    }}

Explanation:

  • First, take the number of elements.

  • Input each element into the array and add it to sum.

  • Average = sum of all elements / number of elements.

  • Cast to (double) to get a decimal result if needed.


Sample Output:

Enter the number of elements: 5Enter 5 numbers:1020304050Average = 30.0

Would you also like a version that finds the average of floating-point numbers (like 5.5, 6.7)? ?
It’s very similar! ?

Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.
html
docker
php
kubernetes
golang
mysql
postgresql
mariaDB
sql