Java conditions, arrays, and loops
Count values that satisfy a boundary condition.
Java
class Main {
public static void main(String[] args) {
int[] scores = {49, 50, 80};
int passed = 0;
for (int score : scores) {
if (score >= 50) passed++;
}
System.out.println(passed);
if (passed != 2) throw new AssertionError("count");
}
}Output
2
Explanation
An enhanced for loop visits each array element. A comparison produces a boolean used by if to decide whether the counter changes.
The >= condition includes a score exactly equal to the pass threshold. The array has a fixed length; the loop reads its elements without changing them.
Explore the dry run
Guided walkthroughReady
1
class Main {2
public static void main(String[] args) {3
int[] scores = {49, 50, 80};4
int passed = 0;5
for (int score : scores) {6
if (score >= 50) passed++;7
}8
System.out.println(passed);9
if (passed != 2) throw new AssertionError("count");10
}11
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create an array of three scores. | scores = [49, 50, 80] | — | |
| Initialize the counter. | passed = 0 | — | |
| 49 fails; 50 passes at the boundary. | passed = 1 | — | |
| 80 also passes. | passed = 2 | — | |
| Print the final count. | passed = 2 | 2 |
Cost and common mistakes
O(n) time and O(1) auxiliary space.
- Replacing >= with > would exclude score 50.
- Changing the copied loop variable does not change the array's primitive element.
Try it yourself
Add score 0 and score 100.
Reveal answer and reasoning
The count becomes 3 because only 100 adds another passing score.