Loops
for
Java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Step " + i);
}
}
}for (start; condition; update): the start runs once, then the body repeats while the condition is true, with the update after each pass. The counter can move however you like:
Java
public class Main {
public static void main(String[] args) {
for (int i = 10; i > 0; i -= 3) {
System.out.print(i + " ");
}
System.out.println();
int sum = 0;
for (int n = 1; n <= 100; n++) {
sum += n;
}
System.out.println("1 + 2 + ... + 100 = " + sum);
}
}while
Java
public class Main {
public static void main(String[] args) {
int balance = 1000;
int years = 0;
while (balance < 2000) {
balance += balance * 8 / 100; // 8% interest a year, in whole rupees
years++;
}
System.out.println("Doubled after " + years + " years: " + balance);
}
}Use while when you don't know in advance how many passes you'll need: here, how many years of interest it takes to double the money.
do-while
This example's input is -3, 0 and 8, one per line:
Java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n;
do {
System.out.print("Enter a positive number: ");
n = in.nextInt();
System.out.println("you typed " + n);
} while (n <= 0);
System.out.println("Thanks, you entered " + n);
}
}A do-while checks its condition at the end, so the body always runs at least once, which is exactly right for "ask until the answer is valid".
The enhanced for
Java
public class Main {
public static void main(String[] args) {
String[] langs = {"Java", "Python", "SQL"};
for (String lang : langs) {
System.out.println("I'm learning " + lang);
}
}
}Read for (String lang : langs) as "for each lang in langs". Use it when you need every element but not its position.
break and continue
Java
public class Main {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) continue; // skip the rest of this pass
if (i > 7) break; // leave the loop entirely
System.out.print(i + " ");
}
System.out.println();
}
}Nested loops
Java
public class Main {
public static void main(String[] args) {
for (int row = 1; row <= 4; row++) {
for (int col = 1; col <= 4; col++) {
System.out.printf("%4d", row * col);
}
System.out.println();
}
}
}The inner loop runs completely for every pass of the outer one: a multiplication table in six lines.
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.