Unit 4: Iteration
This unit covers different types of loops and iteration structures in Java programming.
Key Concepts
- while Loops: Condition-based iteration
- for Loops: Counter-based iteration
- Enhanced for Loops: Iterating over collections
- Nested Loops: Loops within loops
- Loop Control: break and continue statements
- Infinite Loops: Causes and prevention
- Loop Invariants: Understanding loop behavior
Example Code: Basic Iteration
// Example: Different Types of Loops in Java
public class LoopExamples {
public static void main(String[] args) {
// while loop
int count = 0;
while (count < 5) {
System.out.println("While loop count: " + count);
count++;
}
// for loop
for (int i = 0; i < 5; i++) {
System.out.println("For loop count: " + i);
}
// enhanced for loop
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
System.out.println("Fruit: " + fruit);
}
// nested loops
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.println("i=" + i + ", j=" + j);
}
}
// break statement
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println("Count before break: " + i);
}
// continue statement
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
System.out.println("Count with continue: " + i);
}
}
}
Example Code: Advanced Iteration
// Example: Advanced Loop Patterns and Algorithms
public class AdvancedLoopExamples {
public static void main(String[] args) {
// Pattern printing
printPyramid(5);
// Array manipulation with loops
int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
reverseArray(numbers);
printArray(numbers);
// Finding prime numbers
findPrimes(20);
// Matrix operations
int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
transposeMatrix(matrix);
printMatrix(matrix);
}
private static void printPyramid(int rows) {
for (int i = 1; i <= rows; i++) {
// Print spaces
for (int j = 0; j < rows - i; j++) {
System.out.print(" ");
}
// Print stars
for (int k = 0; k < 2 * i - 1; k++) {
System.out.print("*");
}
System.out.println();
}
}
private static void reverseArray(int[] arr) {
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}
}
private static void findPrimes(int limit) {
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
System.out.print(num + " ");
}
}
System.out.println();
}
private static void transposeMatrix(int[][] matrix) {
for (int i = 0; i < matrix.length; i++) {
for (int j = i + 1; j < matrix[i].length; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
}
private static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
private static void printMatrix(int[][] matrix) {
for (int[] row : matrix) {
for (int num : row) {
System.out.print(num + " ");
}
System.out.println();
}
}
}
Iteration and Loops
Common Loop Types:
Loop Type | Description | Example |
---|---|---|
for |
Fixed number of iterations | for (int i = 0; i < 10; i++) |
while |
Condition-based iteration | while (x > 0) |
do-while |
Executes at least once | do { ... } while (condition); |
for-each |
Iterate over collections | for (String s : strings) |
Loop Examples:
// For loop example
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// While loop example
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// Do-while loop example
int num = 0;
do {
System.out.println("Number: " + num);
num++;
} while (num < 5);
// For-each loop example
String[] fruits = {"Apple", "Banana", "Orange"};
for (String fruit : fruits) {
System.out.println(fruit);
}
Loop Control Statements:
// Break statement
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop
}
System.out.println(i);
}
// Continue statement
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
Loop Tips:
- Choose the right loop type for your needs
- Ensure loops have a valid termination condition
- Use meaningful loop variable names
- Be careful with nested loops
- Consider using break and continue when appropriate
Common Pitfalls and Debugging Tips
Common Mistakes:
- Infinite Loops: Missing or incorrect termination condition
while (x > 0) { // Wrong! x never changes System.out.println(x); } while (x > 0) { // Correct! x is decremented System.out.println(x); x--; }
- Off-by-One Errors: Incorrect loop bounds
for (int i = 0; i <= array.length; i++) { // Wrong! ArrayIndexOutOfBounds for (int i = 0; i < array.length; i++) { // Correct! Proper bounds
- Modifying Loop Variables: Changing loop counter inside loop
for (int i = 0; i < 10; i++) { i++; // Wrong! Skips every other iteration System.out.println(i); }
Debugging Tips:
- Use System.out.println() to track loop variables
- Check loop termination conditions
- Verify loop bounds with array lengths
- Test edge cases (empty arrays, single elements)
- Use breakpoints in your IDE
AP Exam Tips:
- Know when to use each type of loop
- Understand loop control statements
- Be able to trace loop execution
- Know how to handle array iteration
- Understand nested loops
AP Exam-Style Practice Problems
Problem 1: Loop Execution
Consider the following code segment:
int sum = 0;
for (int i = 1; i <= 5; i++) {
sum += i;
}
System.out.println(sum);
What is printed as a result of executing the code segment?
The correct answer is A. The loop sums the numbers from 1 to 5, which equals 15.
Problem 2: Nested Loops
Consider the following code segment:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(i + j + " ");
}
System.out.println();
}
What is printed as a result of executing the code segment?
The correct answer is A. The nested loops print the sum of i and j for each combination, with a new line after each inner loop completes.
Problem 3: While Loop
Consider the following code segment:
int x = 10;
while (x > 0) {
x -= 2;
System.out.print(x + " ");
}
What is printed as a result of executing the code segment?
The correct answer is A. The loop decrements x by 2 each iteration until it reaches 0, printing each value.
Problem 4: Loop Control
Consider the following code segment:
int sum = 0;
for (int i = 1; i <= 10; i++) {
if (i % 3 == 0) {
continue;
}
sum += i;
}
System.out.println(sum);
What is printed as a result of executing the code segment?
The correct answer is A. The loop sums all numbers from 1 to 10 except those divisible by 3 (3, 6, 9), resulting in 37.
Interactive Code Playground
Try out your own iteration code here!
Output:
Note: This is a simulated environment. For actual Java code execution, please use an IDE or online Java compiler.
For actual code execution, we recommend using: