Subjects and resources that you bookmark will appear here.

2 min readβ’november 16, 2020

Peter Cao

A **nested iteration** occurs when we have a loop inside of another loop, similar to nested conditional statements back in Unit 3. Here is the general anatomy:

```
loopOne {
loopTwo {
something
}
}
```

When a loop is nested inside another loop, all of the iterations of the inner loop must be completed until the next iteration of the outer loop starts. If there is a break statement inside the inner loop, then it only takes effect in the current iteration of the outer loop. When the next iteration of the outer loop starts, the inner loop starts all over again.

If there are two nested for loops without break statements, and the outer loop runs n times, and the inner loop runs m times for every iteration of the outer loop, then the inner loop will run m*n times. This can be extended to situations where there are more than 2 nested loops. The total number of times the innermost loop is run is the product of the number of times that each loop runs per iteration.

```
import java.lang.Math;
public static void printNextNPrimes(int number, int n) {
currentNumber = number;
for (int i = 0; i < n; i++) {
boolean notPrime = true;
while notPrime {
currentNumber++;
notPrime = false;
for (int i = 2; i < (int) Math.sqrt(currentNumber); i++) {
if (currentNumber % i == 0) {
notPrime = true;
break;
}
}
if (!notPrime) {
system.out.println(currentNumber);
}
}
}
}
```

This is a nested iteration with three loops. The outer loop is a for loop that increments whenever a prime number is found until we get to n prime numbers. The middle loop is a while loop that increments the number being checked until it becomes a prime number. Finally, the inner loop is a for loop that checks all possible divisors to see if the number is a prime number or not. In the while loop, we assume that the number is prime, but once the number is found to be not prime in the for loop, the for loop breaks and the boolean notPrime is set to true. If the number is actually not prime, notPrime remains false and the while loop exits.

Take this quiz for a progress check on what youβve learned this year and get a personalized study plan to grab that 5!

START QUIZSign up now for instant access to 2 amazing downloads to help you get a 5

Browse Study Guides By Unit

π

Exam Reviews

π±

Unit 10: Recursion

β

Unit 1: Primitive Types

π±

Unit 2: Using Objects

π₯

Unit 3: Boolean Expressions and if Statements

πΉ

Unit 4: Iteration

βοΈ

Unit 5: Writing Classes

βοΈ

Unit 6: Array

πΎ

Unit 7: ArrayList

π»

Unit 8: 2D Array

π²

Unit 9: Inheritance

Thousands of students are studying with us for the AP Computer Science A exam.

join now