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.
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.
% 2 != 0
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}?
{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?