4 min read•Last Updated on June 18, 2024
Avanish Gupta
Milo Chang
Avanish Gupta
Milo Chang
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.
public static ArrayList<Integer> findNPrimes(int n) {
int prime = 2;
ArrayList<Integer> primes = new ArrayList<Integer>();
for (int i = 0; i < n; i++) {
[boolean](https://www.fiveableKeyTerm:boolean) notPrime = false;
while (!notPrime) {
for (int j = 2; j < prime; j++){
if (prime % j == 0) {
notPrime = true;
break;
}
}
if (notPrime) {
prime++;
notPrime = false;
} else {
notPrime = true;
}
}
primes.add(prime);
prime++;
}
return primes;
}
Explanation of Code
This is a nested iteration with three loops.
public static void printPyramid(int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
[System.out.print](https://www.fiveableKeyTerm:System.out.print)("*");
}
[System.out.println](https://www.fiveableKeyTerm:System.out.println)();
}
The code above will print out:
**
This is a nested iteration with two loops. In the first loop, we go from 0 to n in order to have n rows in the output. In the second loop, we start from the row number and print n-row number of stars for the row.
Once we exit the second loop, we print an empty line, i is incremented by one, and we enter the second loop to print the stars for the next line.
public static void printPyramid(int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
System.out.print(i+j);
}
System.out.println();
}
The code above will print out:
01234
2345
456
67
8
This is essentially the same code as earlier, except now we print out the sum of the row and column indices. This will allow us to demonstrate the use of break and continue in the next two examples.
public static void printPyramid(int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == 3 && j == 3) {
break;
}
System.out.print(i+j);
}
System.out.println();
}
The code above will print out:
01234
2345
456
8
Notice that this time, because we told the program to break when it reaches the fourth row (when i = 3, since Java uses zero-based indexing) and tries to print the first number on that row (since j is always set to the row index when we start a new row), it completely breaks out of the second loop so nothing is printed in the fourth row.
Once the program breaks out of the second loop, the first loop iterates by one and the program prints the fifth row the same way it did in the example above.
public static void printPyramid(int n) {
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (i == 3 && j == 3) {
continue;
}
System.out.print(i+j);
}
System.out.println();
}
The code above will print out:
01234
2345
456
7
8
This time, instead of using a break, we used a continue. This means that we didn't completely break out of the second loop. We just skipped the iteration that happens when j is 3. (It doesn't print 6.) The second loop continues, iterating j to 4 and printing the 7. Then j is incremented again to be 5, but since that is not less than n (which is also 5), we exit the second loop normally.
Once we exit the second loop, we move on to the fifth row, which is printed normally.
Pay careful attention to the Break in Nested Loops example and the Continue in Nested Loops example, since they illustrate the important difference between break and continue. Break completely exits the loop it is called in; continue just skips the current iteration of the loop it is called in.
A boolean is a data type that can only have two possible values: true or false. It is often used in programming to make decisions and control the flow of a program.
Term 1 of 9
A boolean is a data type that can only have two possible values: true or false. It is often used in programming to make decisions and control the flow of a program.
Term 1 of 9
A boolean is a data type that can only have two possible values: true or false. It is often used in programming to make decisions and control the flow of a program.
Term 1 of 9
Nested iteration refers to the process of using one loop inside another loop. This allows for repeated execution of a block of code within another block of code.
Loop: A loop is a programming construct that allows for repeated execution of a block of code based on certain conditions.
Break Statement: The break statement is used within loops to terminate their execution prematurely based on certain conditions.
Iteration: Iteration refers to the repetition or looping through a set of instructions in order to achieve a desired outcome.
A for loop is a control flow statement that allows you to repeatedly execute a block of code for a specified number of times or until certain conditions are met.
While Loop: A while loop repeatedly executes a block of code as long as a given condition remains true.
Loop Variable: The loop variable is a variable that keeps track of the current iteration or count in a loop.
Nested Loop: A nested loop is a loop inside another loop. It allows you to perform more complex repetitive tasks by iterating over multiple sets of data simultaneously.
A prime number is a positive integer greater than 1 that has no positive divisors other than 1 and itself. In simpler terms, it's a number that cannot be evenly divided by any other numbers except for 1 and itself.
Composite number: A composite number is an integer greater than 1 that can be evenly divided by numbers other than 1 and itself. In contrast to prime numbers, composite numbers have multiple factors.
Sieve of Eratosthenes: The Sieve of Eratosthenes is an algorithm used to find all prime numbers up to a given limit. It works by iteratively marking the multiples of each prime number, gradually eliminating non-prime numbers from a list.
Prime factorization: Prime factorization is the process of expressing a composite number as a product of its prime factors. It involves finding the prime numbers that can divide the given number without leaving any remainder.
A while loop is a control flow statement that allows a block of code to be executed repeatedly as long as a specified condition is true.
Condition: A condition is an expression that evaluates to either true or false, determining whether the code inside the while loop should be executed.
Loop body: The loop body refers to the block of code that gets executed repeatedly as long as the condition in the while loop remains true.
Infinite loop: An infinite loop occurs when the condition in a while loop always evaluates to true, causing the code inside it to repeat indefinitely.
In programming, continue is a keyword used within loops (such as for or while loops) to skip the rest of the current iteration and move on to the next one. It allows you to control which iterations should be executed based on certain conditions.
Break: A keyword used within loops to immediately terminate the loop and continue with the code after it.
Loop: A programming construct that allows a set of instructions to be repeated until a certain condition is met.
Conditional Statement: A statement that performs different actions based on whether a specific condition is true or false.
Zero-based indexing is a numbering system where the first element in an array or list is assigned index 0 instead of 1. This means that elements are accessed by their position relative to zero.
Array: A data structure that stores multiple values of the same type in contiguous memory locations.
Index Out Of Bounds Exception: An error that occurs when trying to access an element outside the valid range of indices in an array or list.
Length/Size Property: A property associated with arrays or lists that returns the number of elements they contain.