Arrays let a loop visit real data rather than values calculated from the loop counter. An indexed loop starts at 0 and continues while index < length. Use the index to read or update each element. The condition excludes length itself, which prevents the out-of-bounds mistake from the previous lesson.
An enhanced for loop, for (int value : values), visits each int in order
without exposing its position. Read the colon as “in”. Prefer this form when you
need values but not indexes. Use an indexed loop when you must replace elements
or report their positions. Both forms handle an empty array by running zero times.
Reuse the accumulator pattern
The pattern from Day 2 still works: initialize before the loop, update inside, return or report after it. To count matching values, add one when the condition holds. To total matching values, add the value instead. Keeping those operations separate avoids a common confusion between “how many sessions” and “how much time”.
State what happens on empty input. A total naturally starts at zero, so an empty sum is zero. An average needs a separate rule because division by zero is not a meaningful empty average. Do not invent an element at index 0 to initialize a sum; zero is already a useful neutral starting value.
public class Main {
public static void main(String[] args) {
int[] minutes = {10, 25, 40};
for (int index = 0; index < minutes.length; index++) {
System.out.println(index + ": " + minutes[index]);
}
}
}Check your prediction
0: 10
1: 25
2: 40 There are three body executions. The final condition checks index=3 and stops. If you use <=, the first three lines print before the fourth access fails; partial output does not mean the program completed successfully.
public class Main {
public static void main(String[] args) {
System.out.println(total(new int[] {10, 25, 40}));
System.out.println(total(new int[] {}));
}
static int total(int[] values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return sum;
}
}Check your prediction
75
0 Inside a method call, new int[] supplies an array expression. The helper reads it without needing separate variables for every input. It does not change the supplied array.
public class Main {
public static void main(String[] args) {
int[] minutes = {10, 25, 40};
int count = 0;
int selectedTotal = 0;
for (int value : minutes) {
if (value >= 25) {
count++;
selectedTotal += value;
}
}
System.out.println(count);
System.out.println(selectedTotal);
}
}Check your prediction
2
65 The condition selects two values, but their total is 65, not 2. Trace both columns for the same input. Changing >= to > removes the boundary value 25 from both results.
Your turn
Return a total for any array
Implement total(int[] values). Assume values refers to an actual array; it can be empty. A missing array, represented by null, is outside this exercise. The editor checks {10,25,40}→75, empty→0, {7}→7 and {-2,5}→3. Do not assume there are exactly three elements or change the input. Its normal main prints 75.
public class Main {
public static void main(String[] args) {
System.out.println(total(new int[] {10, 25, 40}));
}
static int total(int[] values) {
return 0; // Replace the placeholder.
}
}Hint 1: the idea
Use a neutral starting total and visit every supplied value. Negative values still participate in ordinary addition.
Hint 2: a first step
Create sum before an enhanced for loop. Return it after the loop rather than returning on the first iteration.
Show one solution
public class Main {
public static void main(String[] args) {
System.out.println(total(new int[] {10, 25, 40}));
}
static int total(int[] values) {
int sum = 0;
for (int value : values) {
sum += value;
}
return sum;
}
}75 Change it and explain
Write an indexed version of total and compare it with the enhanced-for version. Then implement a countAtLeast method with both an array and a threshold parameter. For {10,25,40} and 25 it should return 2; for an empty array it should return 0.
Explain why assigning a different number to the enhanced-for variable does not replace an array element. That variable holds the current int value. If you want to update the stored elements, use values[index] in an indexed loop deliberately.
Completion is saved in this browser only. It does not measure mastery.