DSA Factory
Free lessonsArrays · Stage 1 · Traversal · Step 2

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.

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
Quick check

How many even numbers are in 3, 8, 0, 5?

  1. A1
  2. B2
  3. C3
Show the answer

2. 8 and 0 are even. 3 and 5 leave 1 over.

Your problem

Count the evens

Return how many numbers in the list are even. Zero and negative numbers can be even too.

Example
nums = [4, 7, 2, 9, 6] → 3

0 ≤ n ≤ 1,000

Solve it in your browserPython, C++, Java or JavaScript. Hints if you get stuck. No sign-up needed.
Start coding