Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Find Array Average

How To Calculate the Average of Array Elements

Craft a program that computes the average age from a set of diverse ages.

Example

// An array storing different ages
int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float
avg, sum = 0;
// Get the length of the array
int length = ages.length;
// Loop through the elements of the array
for (int age : ages) {
  sum += age;
}
// Calculate the average by dividing the sum by the length
avg = sum / length;
// Print the average
System.out.println("The average age is: " + avg);