Decisions and loops

A program becomes interesting when it can decide and repeat. if runs a block only when its condition is true; else runs otherwise. Conditions compare values with <, >, <=, >=, == (equal) and != (not equal), and combine them with && (and) and || (or).

A for loop repeats a block while a counter goes through a range:

1 Counting Count.java ● in the editor

public class Count {
    public static void main(String[] args) {
        for (int i = 1; i <= 5; i++) {
            if (i % 2 == 0) {
                System.out.println(i + " is even");
            } else {
                System.out.println(i + " is odd");
            }
        }
    }
}

The three parts of for (int i = 1; i <= 5; i++) are: start with i = 1; keep going while i <= 5; after each round, add one to i (i++). A while (condition) { … } loop repeats as long as its condition is true; it is the right choice when you do not know in advance how many rounds you need. A loop whose condition never becomes false runs forever: press Stop to end it.

Print the numbers from 1 to 15, but print Fizz instead of numbers divisible by 3, Buzz instead of numbers divisible by 5, and FizzBuzz instead of numbers divisible by both. Hint: n % 3 == 0 is true when n is divisible by 3, and the order of your checks matters.

2 Exercise: FizzBuzz FizzBuzz.java ○ to do

public class FizzBuzz {
    public static void main(String[] args) {
        for (int n = 1; n <= 15; n++) {
            System.out.println(n);
        }
    }
}
Terminal

Editor.sh · Learn to program by writing and running real code in your browser. Nothing to install; your work stays in this browser.

© 2026 xuwaters.com

Step 1 of 2Counting