Unit 4 Iteration Notes

  • While loops: repeats lines of code until a certain condition evaluates to false
  • While loops consist of 2 portions: the boolean expression and the brackets which store the looping code inside.
int[] array = {3, 7, 0, 2, 4, 5, 9, 1, 3, 6, 3};
int total = 0;
int i = 0;

while (i < array.length) {
    total += array[i];
    i++;
}

System.out.println(total);
  • 3 parts of a foor loop: initialization of a variable, test condtions, loop body
  • The code in the initialization area is executed only one time before the loop begins
  • the test condition is checked each time through the loop and the loop continues as long as the condition is true
for (int x = 1; x <= 5; x++) {
    System.out.println(x);
}
  • Strings can also be manipulated through the use of iteration. Strings can actually be thought of as an array of chars, so each char can also be manipulated as well!
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
for (int row = 0; row < 5; row ++) {
    for (int column = 0; column < 4; column++) {
        System.out.print('*');
    }
    System.out.println();
}
  • As the name suggests, for-each loops are similar to for loops. In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList). It is also known as the enhanced for loop.
  • array: an array or collection, item: each value in an array or collection, dataType: specify the type of data in the array (int) -makes code easier to read and understand
  • eliminates possible coding mistakes
  • The drawback of the enhanced for loop (for-each loop) is that it cannot traverse the elements in reverse order. In the for each loop you do not have the option to skip any element because it does not work on an index basis. Moreover, you cannot traverse the odd or even elements only.
//For Each Loop
char[] word = {'m', 'o', 'n', 'k', 'e', 'y'};
  
for (char letter: word) {
  System.out.println(letter);
}