Iteration Notes
Iteration Notes
- 4.1 While Loops (2.B, 3.C)
- 4.2 For Loops
- Three Parts of a For Loop
- 4.3 Loops and Strings
- 4.4 Nested Iteration
- For Each Loops
while (condition) {
...
}
The boolean expression is checked before the loop is started and every time the loop ends and is about to start anew. Usually, inside the loop something is done that slightly changes the conditions for the boolean expression until it reads false and ends. In the example below, the condition is x > 0, meaning that x has to be changed for the loop to stop. Inside the loop, x is decremented by 1 every time, changing the conditions over and over again until it finally returns false and terminates the while loop.
int x = 5;
// The boolean expression in this case is x > 0
while (x > 0) {
System.out.println(x);
x--;
}
for (initialize; test condition; change)
{
loop body
}
for (int x = 1; x <= 5; x++) {
System.out.println(x);
}
String name = "CodeCodeCode";
for (int i = 0; i < name.length(); i+=2) {
System.out.println(name.substring(i,i+2));
}
Nested iteration is where there is a loop within a loop. It's kind of similar to the nested conditional that we learned yesterday in syntax.
A typical usage of nested looping is for two dimensions, like getting the pixel value of each pixel in an image across the columns and rows of pixels. Or, it can be used to print across these rows and columns to display some text
A very common nested iteration is the use of nested for loops, as they are concise enough to be used within each other without getting confused. Here is an example of code that uses nested for loops:
for (int row = 0; row < 5; row ++) {
for (int column = 0; column < 4; column++) {
System.out.print('*');
}
System.out.println();
}
As seen, the code above has an output of 20 stars, with 5 rows and 4 columns. The amount of times the nested iterations loop in total will be the amount the outer one iterates multiplied by the inner one. The inner loop must finish all of its iterations before the outer loop can continue.
Question:
- What happens if you swap the inner with the outer loop? What change will the output make?
There can also be nested while loops, although they are not as practical, having to write out those variables outside of the condition.
Here is the syntax for a for-each loop:
for(dataType item : array) {
...
}
includes:
- array: an array or collection
- item: each value in an array or collection
- dataType: specify the type of data in the array (int)
Example
public class ForEachLoops {
public static void main(String[] args) {
// create an array
int[] data = {2, 10, 5, 12};
// for each loop
for (int number: data) {
System.out.println(number);
}
}
}
Output:
2 10 5 12