Lesson 6 of 20

Loops

Loops

for Loop

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

while Loop

int n = 3;
while (n > 0) {
    System.out.print(n + " ");
    n--;
}
// prints: 3 2 1

for-each Loop

Iterate over arrays or collections:

String[] fruits = {"apple", "banana", "cherry"};
for (String fruit : fruits) {
    System.out.println(fruit);
}

break and continue

for (int i = 0; i < 10; i++) {
    if (i == 3) continue;  // skip 3
    if (i == 6) break;     // stop at 6
    System.out.print(i + " ");
}
// prints: 0 1 2 4 5

Your Task

  1. Use a for loop to sum integers 1 through 5, print the sum
  2. Use a while loop to print 3 2 1 (note the trailing space)
  3. Use a for-each loop over {"apple", "banana", "cherry"}, printing each on its own line
TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.