Introduction

An algorithm is a repeatable procedure for solving a problem. Counting values is one example: begin with zero, inspect each item, and update the count when it matches. Check the empty collection and a collection with no matches.

Syntax & example

public class Main {
  public static void main(String[] args) {
    int[] numbers = {2, 5, 8, 11, 14};
    int count = 0;
    for (int number : numbers) {
      if (number % 2 == 0) count++;
    }
    System.out.println(count);
  }
}

Expected output

3

Common mistakes

  • Using a variable before assigning a value to it.
  • Mixing text and numbers without converting deliberately.
  • Skipping an empty input or a boundary value when testing.

Practice

Change the numbers and predict how many even values remain.

13px
Main.javaYour ideas, in code.
Loading your editor…
Run your code to see the output here.
Ready to buildUTF-810 lines