Foundation

05 โ€” Loops

Previous: 04 Control Flow ยท Next: 06 Methods

โ–ถ๏ธ java pkg1core/core6Loops.java


for loop โ€” when you need an index

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

Three parts: init โ†’ condition โ†’ update.


Enhanced for (for-each)

java
1int[] nums = {10, 20, 30};2for (int n : nums) {3    System.out.println(n);4}

๐Ÿ’ก Use for-each when you need each element, not the index.


while loop

java
1int count = 3;2while (count > 0) {3    System.out.println(count);4    count--;5}

Checks condition before each iteration. May run zero times.


do-while loop

java
1int x = 0;2do {3    System.out.println("Runs at least once");4} while (x > 0);

Body runs at least once, then checks condition.


break and continue

java
1for (int i = 1; i <= 10; i++) {2    if (i % 2 == 0) continue;   // skip evens3    if (i > 7) break;           // stop loop4    System.out.print(i + " ");5}6// 1 3 5 7
Keyword Effect
break Exit the loop entirely
continue Skip to next iteration

Labeled break (nested loops)

java
1outer:2for (int i = 1; i <= 5; i++) {3    for (int j = 1; j <= 5; j++) {4        if (i + j == 7) {5            break outer;   // exits both loops6        }7    }8}

Use sparingly โ€” often a method extraction is clearer.


Which loop to choose?

Loop Best for
for Known iterations, need index
for-each Iterate every element
while Unknown iterations, condition-driven
do-while Must run at least once (menus, input validation)

Practice

  1. Run core6Loops.
  2. Print multiplication table 1โ€“10 with nested for loops.
  3. Sum array elements with for-each.

Next โ†’ 06 Methods Related โ†’ 01 Core Java