AI Hints
Home›Java Tutorial›break and continue, Nested Loops and Loop Patterns
Java · Lesson 42 of 120

Loop Patterns

Find, count, check.

⏱ 2 min read▶ Video at 53:10🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

A few loop patterns come up again and again. Finding the biggest value, counting matches, and checking if anything matches. Let's learn them, with a list of temperatures.

  • Find the biggest
  • Count matches
  • Check for any

Three patterns

Here's a small list of temperatures, called an array. We'll learn arrays properly, in the next module. This for loop visits each temperature in turn. To find the biggest, start with the first value, and replace it whenever we see a bigger one. To count, add one each time a value matches. And to check if any day was freezing, start with false, and switch to true if one matches. Run it. The hottest day was twenty seven. Three days were above twenty. And none were freezing.

Main.javajava
public class Main {
    public static void main(String[] args) {
        int[] temps = {18, 23, 15, 27, 21};
        int max = temps[0];
        int hot = 0;
        for (int t : temps) {
            if (t > max) max = t;
            if (t > 20) hot++;
        }
        System.out.println("Hottest: " + max);
        System.out.println("Days above 20: " + hot);
        boolean anyFreezing = false;
        for (int t : temps) {
            if (t <= 0) anyFreezing = true;
        }
        System.out.println("Any freezing day? " + anyFreezing);
    }
}
Output
Hottest: 27
Days above 20: 3
Any freezing day? false

The patterns

These three patterns appear in almost every program. Each has a starting value, and an update inside the loop.

PatternStartInside the loop
Biggestmax = first valueif (t > max) max = t
Countcount = 0if (match) count++
Any?found = falseif (match) found = true

Summary

To find the biggest, count matches, or check for any, start with a value, and update it inside the loop. Next, counting, and summing.

Key takeaways
  • max pattern
  • count pattern
  • any pattern
Next up: Counting and Summing — running totals