Common Array Operations
Part of the Fundamentals section of Coddy's Java journey — lesson 66 of 73.
Here are some common array operations:
- Find the sum of all elements in an array:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
System.out.println("Sum: " + sum);- Find the average of elements in an array:
int[] numbers = {1, 2, 3, 4, 5};
int sum = 0;
for (int number : numbers) {
sum += number;
}
double average = (double) sum / numbers.length;
System.out.println("Average: " + average);- Find the maximum element in an array:
int[] numbers = {1, 5, 2, 9, 3};
int max = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > max) {
max = numbers[i];
}
}
System.out.println("Max: " + max);- Find the minimum element in an array:
int[] numbers = {1, 5, 2, 9, 3};
int min = numbers[0];
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] < min) {
min = numbers[i];
}
}
System.out.println("Min: " + min);Challenge
EasyCreate a method named calculateStats that takes an array of integers as input and performs the following operations:
- Calculates the sum of all elements in the array.
- Calculates the average of the elements in the array.
- Finds the maximum element in the array.
- Finds the minimum element in the array.
The method should return an array of doubles containing the sum, average, maximum, and minimum, in that order.
Try it yourself
import java.util.Scanner;
public class Main {
public static double[] calculateStats(int[] arr) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String text = scanner.nextLine();
String[] arrString = text.split(",");
int[] numbers = new int[arrString.length];
for (int i = 0; i < arrString.length; i++) {
numbers[i] = Integer.parseInt(arrString[i]);
}
double[] stats = calculateStats(numbers);
System.out.println("Sum: " + stats[0]);
System.out.println("Average: " + stats[1]);
System.out.println("Maximum: " + stats[2]);
System.out.println("Minimum: " + stats[3]);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else