06 - Loops
Loops
What is it?
A loop repeats a block of code multiple times. Instead of writing the same line 10 times, you write it once and tell the loop how many times to run it.
The while Loop
The most fundamental loop. Keeps running as long as the condition is true.
while (condition) {
// code to repeat
}
Example - count from 1 to 5
int i = 1;
while (i <= 5) {
System.out.println(i);
i++; // increment - without this, loop runs forever!
}
// Output: 1 2 3 4 5
The while (true) + break Pattern
Use this when you want to loop until the user gives valid input, or until some event happens inside the loop. You control when to stop using break.
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("Enter a positive number:");
int number = Integer.parseInt(scanner.nextLine());
if (number > 0) {
break; // exits the loop
}
System.out.println("That's not positive. Try again.");
}
System.out.println("Thank you!");
The recommended loop structure (from the course)
Scanner scanner = new Scanner(System.in);
// 1. Create any variables you need before the loop
int sum = 0;
while (true) {
// 2. Read input
String input = scanner.nextLine();
// 3. Check exit condition - break if done
if (input.equals("done")) {
break;
}
// 4. Check for invalid input - skip with continue
int number = Integer.parseInt(input);
if (number < 0) {
continue; // goes back to the top of the loop
}
// 5. Handle valid input
sum += number;
}
// 6. Code after the loop
System.out.println("Sum: " + sum);
break vs continue
| Keyword | What it does |
|---|---|
break |
Exits the loop entirely - jumps to the code after the loop |
continue |
Skips the rest of this iteration - jumps back to the top of the loop |
// continue example - skip even numbers
int i = 0;
while (i < 10) {
i++;
if (i % 2 == 0) {
continue; // skip even numbers
}
System.out.println(i); // prints 1, 3, 5, 7, 9
}
The for Loop
Best used when you know exactly how many times you want to loop:
for (int i = 0; i < 5; i++) {
System.out.println(i); // prints 0, 1, 2, 3, 4
}
Breaking it down:
for ( initializer ; condition ; update ) { body }
int i = 0 i < 5 i++
- Initializer: runs once at the start (
int i = 0) - Condition: checked before every iteration; loop stops when false (
i < 5) - Update: runs after each iteration (
i++)
while vs for - when to use which
Use while when… |
Use for when… |
|---|---|
| You don’t know how many iterations | You know the exact count |
| You’re waiting on user input | Iterating over a range or list |
| The exit condition is complex | Simple counter-based loops |
Nested Loops
A loop inside a loop. The inner loop completes all its iterations for each single iteration of the outer loop:
for (int row = 1; row <= 3; row++) {
for (int col = 1; col <= 3; col++) {
System.out.print(row + "," + col + " ");
}
System.out.println(); // newline after each row
}
// Output:
// 1,1 1,2 1,3
// 2,1 2,2 2,3
// 3,1 3,2 3,3
Gotchas
- Infinite loop: forgetting to increment
ior forgettingbreakin awhile(true)loop - your program hangs forever - Off-by-one error:
i < 5runs 5 times (0–4).i <= 5runs 6 times (0–5). Think carefully about<vs<= - Variables declared inside a loop are reset every iteration - declare accumulators (like
sum) before the loop continueinside aforloop still executes the update (i++) - it only skips the body