Course contentsShow
← Java
Lesson 167 of 2,8704. Control Flow StructuresFree lesson

Common for Loop Patterns: Counting Up and Down

Practice writing loops that count forward, backward, and by custom increments.

Common for Loop Patterns: Counting Up and Down

What you'll learn: How to write for loops that count in different directions and by different increments.

The Core Patterns

Once you understand the traditional for loop's syntax, you'll find yourself using a few common patterns over and over. Think of these like recipes: same basic structure, different ingredients.

Counting Up by 1 (The Classic)

for (int i = 0; i < 5; i++) {
    System.out.println(i);  // Prints: 0, 1, 2, 3, 4
}

This starts at 0 and increases by 1 each time until reaching 4.

Counting Down

for (int i = 5; i > 0; i--) {
    System.out.println(i);  // Prints: 5, 4, 3, 2, 1
}

Here we decrement instead of increment. The condition changes to i > 0 to stop at 1. Think of it like a countdown timer.

Counting by Custom Increments

for (int i = 0; i <= 10; i += 2) {
    System.out.println(i);  // Prints: 0, 2, 4, 6, 8, 10
}

Using i += 2 makes the loop skip every other number — perfect for even numbers. You can use any increment: i += 3 for multiples of three, i += 5 for fives, and so on.

Counting Down by Custom Increments

for (int i = 10; i >= 0; i -= 2) {
    System.out.println(i);  // Prints: 10, 8, 6, 4, 2, 0
}

Combine decrementing with custom steps: i -= 2 counts backward by twos.

Why This Matters

These patterns appear constantly: processing array elements, repeating actions a specific number of times, generating sequences, or creating visual patterns. Master these basics, and you'll write loops confidently.

Key Takeaway: For loops can count up or down, starting anywhere and changing by any increment — adjust the initialization, condition, and update to match your needs.