  The AP Computer Science A 5-hour live stream review is here! 💻

Join us on May 5, 2021 for the 🌶️ AP Computer Science A Cram Finale for a last minute review to get all your questions answered!

# 4.4 Nested Iteration 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.

## Example: Generating the Next N Prime Numbers After a Certain Number

```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); } } } }```
Explanation of Code
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.

##### 💪🏽 Are you ready for the Comp Sci exam?
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 QUIZ
##### FREE AP comp sci a Survival Pack + Cram Chart PDF
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 5: Writing Classes
⌚️
Unit 6: Array
💾
Unit 7: ArrayList
💻
Unit 8: 2D Array
🖲
Unit 9: Inheritance