Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

6.2 Data sets — counting with a condition

Lesson

How many values meet a condition?

A common data-set question is how many values satisfy a condition. Keep a counter at 0, visit each value, and add 1 when the condition is true. The condition can use parameters — for example, counting the scores that fall between lo and hi.


Worked example

int[] scores = {55, 72, 88, 91, 60, 45};
int count = 0;
for (int s : scores) {
    if (s >= 60 && s <= 89) {
        count++;
    }
}
System.out.println(count);   // 3

The condition s >= 60 && s <= 89 is true for 72, 88, and 60, so the count is 3. Using >= and <= makes both bounds inclusive.


▶ Try it: run this, then change the range in the if or the scores and re-run.



You increment the counter when...


s >= 60 && s <= 89 is true when...


Type exactly what this program prints.

int[] d = {65, 70, 80, 55, 90};
int count = 0;
for (int s : d) {
    if (s >= 70 && s <= 89) {
        count++;
    }
}
System.out.println(count);

The counter should start at...


True or false?