Counting made neat
When you know how many times to repeat, a for loop puts everything in one line:
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Lap " + i);
}
}
}Output
Lap 1 Lap 2 Lap 3 Lap 4 Lap 5
The three parts inside the brackets, separated by ;:
| Part | Here | Meaning |
|---|---|---|
| start | int i = 1 | make a counter, once, before the loop |
| condition | i <= 5 | keep going while this is true |
| step | i++ | after each round, add 1 to the counter |
Counting in other ways
public class Main {
public static void main(String[] args) {
for (int i = 10; i >= 1; i--) {
System.out.print(i + " ");
}
System.out.println("Lift off!");
for (int i = 0; i <= 20; i += 5) {
System.out.print(i + " ");
}
System.out.println();
}
}Output
10 9 8 7 6 5 4 3 2 1 Lift off! 0 5 10 15 20
A times table
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 1; i <= 5; i++) {
System.out.println(n + " x " + i + " = " + (n * i));
}
}
}Input (what the user types)
7
Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35
Tip: Use
forwhen you know how many times to repeat. Usewhilewhen you repeat until something happens.