Exit
  1. Learn
  2. Check
  3. Solve
  4. Reflect

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.

Look at every box: but only count the ones that pass.
Count the even ones
4
0
7
1
2
2
9
3
6
4
i

4 divided by 2 leaves nothing over, so it's even. The count becomes 1.

Move 1 of 5

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?".

Even: nothing left over after dividing by 2.
Negative numbers: can leave −1, so test for 0.
In code
count = 0
for x in nums:
    if x % 2 == 0:
        count += 1
return count