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

5.2 Array algorithms — searching and counting

Lesson

Looking for and tallying elements

Two more scan patterns. A linear search checks elements one by one to decide whether a value is present — you can stop as soon as you find it. Counting keeps a counter (starting at 0) and adds 1 each time an element meets a condition.


Worked example — count the even numbers

int[] nums = {4, 7, 2, 9, 6};
int count = 0;
for (int i = 0; i < nums.length; i++) {
    if (nums[i] % 2 == 0) {
        count = count + 1;
    }
}
System.out.println(count);   // 3

▶ Try it: run this to count even numbers. Change the array or the condition (try % 2 != 0 for odds) and re-run.



A linear search checks elements one by one to see whether a value is...


How many even numbers are in {4, 7, 2, 9, 6}?


To count matches, you ___ a counter each time the condition is true.


Type how many even numbers this counts:

int[] a = {2, 3, 4, 5, 6};
int count = 0;
for (int i = 0; i < a.length; i++) {
    if (a[i] % 2 == 0) { count = count + 1; }
}
System.out.println(count);

True or false?