×

java · level 1 · unit 5 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Put an if inside a loop to check every number.

A loop's block can hold any code, an if. We say the if is inside the loop. The loop visits each number, and the if decides what to do with it.

Remember %, the remainder? A number is even when it splits into twos with nothing left over. So house % 2 == 0 is true for even numbers and false for odd ones.

To count matches, make a counter holding 0 before the loop. Each time the if finds a match, add one. Print the total after the loop.

public class Main {
    public static void main(String[] args) {
        int leaflets = 0;
        for (int house = 1; house <= 6; house++) {
            if (house % 2 == 0) {
                System.out.println("Leaflet for house " + house);
                leaflets++;
            }
        }
        System.out.println("Leaflets posted: " + leaflets);
    }
}

Every { needs its own }, so close the if block before the loop's block.