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:
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.
public class FizzBuzz {
public static void main(String[] args) {
for (int n = 1; n <= 15; n++) {
System.out.println(n);
}
}
}