Count what matches
Count the even numbers. About 6 minutes.
Check each value as you pass it
A teacher going through a stack of answer sheets makes a tally mark each time they see a pass. They look at every sheet, but only some of them get a mark.
Counting in a loop works the same way. Start a count at 0. At each box, ask a yes-or-no question with an if. Add 1 to the count only when the answer is yes.
4 divided by 2 leaves nothing over, so it's even. The count becomes 1.
What makes a number even
A number is even when it splits into two equal halves with nothing left over. The remainder operator, written %, tells you what's left over after dividing. So a number is even when its remainder after dividing by 2 is 0.
That test works for 0 (which is even) and for negative numbers too. One catch: in Java, C++ and JavaScript the remainder of −7 by 2 is −1, not 1. So test "is the remainder 0?", not "is it 1?".
count = 0
for x in nums:
if x % 2 == 0:
count += 1
return countHow many even numbers are in 3, 8, 0, 5?
- A1
- B2
- C3
Show the answer
2. 8 and 0 are even. 3 and 5 leave 1 over.
Count the evens
Return how many numbers in the list are even. Zero and negative numbers can be even too.
nums = [4, 7, 2, 9, 6] → 3
0 ≤ n ≤ 1,000