Iteration in Java

Lesson Purpose: Review types of iteration and usages

Lesson Objectives:

  1. review while/for loops
  2. review string
  3. nested iteration review

Iteration may be one of the most crucial features for any programming language, since they allow computers to do what they do best: do copious amounts of menial tasks quickly and efficiently.

Of course, Java can also perform iteration using numerous different structures. Today we'll be going over some of them.

First of all, the exam weights Iteration as 17.5-22.5% of the test, with 7-9 MC and part of FRQ 1. This is one of the largest if not the largest unit, so understanding how iteration works is critical to performance on the test as well as in basically all aspects of coding.

The overall purpose of iteration is to simplify code by allowing it to repeat. Loops will usually include some sort of conditional to check against, and while that conditional is true, the code within the loop will repeat.

4.1 While Loops (2.B, 3.C)

  • 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.

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--;
}
5
4
3
2
1

One of the most basic applications of while loops is its ability to iterate over numerous elements. One such example would be summing up the numbers in an array:

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);
43

One unique application of while loops lie in infinite while loops, loops that run over and over again permanently. This is usually accomplished by setting the boolean condition to be true at all times. The only way to stop these loops are to use a break command, which ends the loop regardless of the conditions present.

This can be used for various things, like having a running process at all times or constantly taking in input from the user, like the example below:

import java.util.Scanner;

Scanner input = new Scanner(System.in);
String choice;

while (true) {
    System.out.println("Would you like to continue: ");
    choice = input.nextLine();
    if (choice.equals("No")) {
        break;
    }
}
Would you like to continue: 
Would you like to continue: 
Would you like to continue: 

Do While loop

Do while loops are a variant of the while loop, where the code must be run first and then the condition is checked. In a normal while loop, the condition is checked then the code is run. So, a do while loop is forced to run at least once, which could be useul.

int i=1;    
do{    
    System.out.println(i);    // forced to run
    i++;    
}while(i<1);
1
int i = 1;
while(i<1) { // starts out false
    System.out.println(i);    
    i++; 
}

Hacks

Say you have a company that makes a profit of $5,450,000 this year. Every year, the company has a profit increase of 5%. Determine how many years it would take to make a profit of at least $30,000,000 using a while loop.

public class WhileLoops {

    public static void main(String[] args) {

    }
}

WhileLoops.main(null);

4.2 For Loops

  • One of the most tested concepts in the APCSA exam
  • Skills 3.C, 4.C, and 5.C

Three Parts of a For Loop

  • Initialization of a variable
  • Test condition
for (initialize; test condition; change)
{
   loop body
}

Example

for (int x = 1; x <= 5; x++) {
    System.out.println(x);
}
1
2
3
4
5

Control Flow Diagram

image

  • 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
  • the loop control variable change is done at the end of each execution of the body of the loop
  • When the loop condition is false, execution will continue at the next statement after the body of the loop.

Hacks

- Change the code above to iterate instead from 1-5 to 10-15. (Print numbers 10-15)

- Convert 10 numbers of your choice from two temperature units (F to C, C to F, C to K)

public class ForLoops {

    public static void main(String[] args) {

    }
}

ForLoops.main(null);

4.3 Loops and Strings

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));
}
Co
de
Co
de
Co
de

4.4 Nested Iteration

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.

import java.util.ArrayList;

/*
 * Creator: Nighthawk Coding Society
 * Mini Lab Name: Hello Series,featuring Monkey Jumpers
 */

/**
 * Class for Monkey: a 2D array of Monkey
 * As well as method to print the Poem
 */
class Monkey {
    //The area between class definition and the 1st method is where we keep data for object in Java
    private static ArrayList<String[]> monkeyList = new ArrayList<String[]>();    //2D Array: AP CSA Unit 8: 2D array of strings
    private String[] monkeyASCII;

    /**
     * Constructor initializes a 2D array of Monkey
     */
    public Monkey(String[] monkeyASCII) {
        this.monkeyASCII = monkeyASCII;
        monkeyList.add(monkeyASCII);
    }

    /**
     * Loop and print monkey in array
     * ... repeat until you reach zero  ...
     */
    public static void printPoem() {
        //begin the poem
        System.out.println();
        System.out.println("Monkey Jumpers Poem in Java with Objects!!!");

        // monkey (non-primitive) defined in constructor knows its length
        int monkeyCount = monkeyList.size();
        for (int i = 1; i <= monkeyCount; i++)  //loops through 2D array length forwards
        {

            //this print statement shows current count of Monkey
            //  concatenation (+) of the loop variable and string to form a countdown message
            System.out.println(i + " little monkey jumping on the bed...");

            //how many separate parts are there in a monkey monkey?
            for (int row = 0; row < i; row++) {  //cycles through "cells" of 2d array

                /*cycles through columns to print
                each monkey part by part, will eventually print entire column*/
                for (int col = 0; col < monkeyList.get(row).length; col++) {

                    // prints specific part of the monkey from the column
                    System.out.print(monkeyList.get(row)[col] + " ");

                    //this is new line between separate parts
                    System.out.println();
                }
                
                //this new line gives separation between stanza of poem
                System.out.println();
            }

            //countdown for poem, decrementing monkeyCount variable by 1
            monkeyCount -= 1;
        }

        //out of all the loops, prints finishing messages
        System.out.println("Too many monkeys jumping on the bed");
        System.out.println("0000000000000000000000000000000000");
        System.out.println("             THE END              ");
    }

   
    /**
    * A Java Driver/Test method that is the entry point for execution
    */
    public static void main(String[] args)  {
        Monkey monkey0 = new Monkey(new String[]{
            "ʕง ͠° ͟ل͜ ͡°)ʔ ",      //[0][0] eyes
            "  \\_⏄_/  ",      //[0][1] chin
            "  --0--   ",       //[0][2] body
            "  ⎛   ⎞   "        //[0][3] legs
        });
        Monkey monkey1 = new Monkey(new String[]{
            " ʕ༼ ◕_◕ ༽ʔ",       //[1][0]
            "  \\_⎏_/  ",
            "  ++1++  ",
            "   ⌋ ⌊   "
        });
        Monkey monkey2 = new Monkey(new String[]{
            " ʕ(▀ ⍡ ▀)ʔ",       //[2][0]
            "  \\_⎐_/ ",
            "  <-2->  ",
            "  〈  〉 "
        });
        Monkey monkey3 = new Monkey(new String[]{
            "ʕ ͡° ͜ʖ ° ͡ʔ",        //[3][0]
            "  \\_⍾_/  ",
            "  ==3==  ",
            "  _/ \\_  "
        });
        Monkey monkey4 = new Monkey(new String[]{
            "  (◕‿◕✿) ",          //[4][0]
            "  \\_⍾_/ ",          //[4][1]
            "  ==4==  ",          //[4][2]
            "  _/ \\_ "           //[4][3]
        });

        
        Monkey.printPoem();   //a new monkey list and output in one step
    }

}

Monkey.main(null);
Monkey Jumpers Poem in Java with Objects!!!
1 little monkey jumping on the bed...
ʕง ͠° ͟ل͜ ͡°)ʔ  
  \_⏄_/   
  --0--    
  ⎛   ⎞    

2 little monkey jumping on the bed...
ʕง ͠° ͟ل͜ ͡°)ʔ  
  \_⏄_/   
  --0--    
  ⎛   ⎞    

 ʕ༼ ◕_◕ ༽ʔ 
  \_⎏_/   
  ++1++   
   ⌋ ⌊    

3 little monkey jumping on the bed...
ʕง ͠° ͟ل͜ ͡°)ʔ  
  \_⏄_/   
  --0--    
  ⎛   ⎞    

 ʕ༼ ◕_◕ ༽ʔ 
  \_⎏_/   
  ++1++   
   ⌋ ⌊    

 ʕ(▀ ⍡ ▀)ʔ 
  \_⎐_/  
  <-2->   
  〈  〉  

Too many monkeys jumping on the bed
0000000000000000000000000000000000
             THE END              

Some modification to the code has been made, such as making monkeys an object, but the overall idea remains the same. It first iterates into a row on the 2d array, and then iterates through all columns of that row in the 2d array by using the nested iteration.

Questions:

  1. Do you remember how to make it not backwards?
  2. What would swapping the inner and outer loops do? (assuming that array indices are fixed)
  3. What if we only wanted to print every other monkey?
  4. What if we wanted to print every other body part of the monkey?
public class NestedIteration {

    public static void main(String[] args) {

    }
}

NestedIteration.main(null);

For Each Loops or enhanced for loops

What is a for each loop?

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.

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

In this example we used for each loops to iterate through the array, "data" and print out each number. The code is saying that for each value in the array, print out the number.

So why not just stick to the for loop? What's the purpose?

//For Loop
char[] word = {'m', 'o', 'n', 'k', 'e', 'y'};

for (int i = 0; i < word.length; ++ i) {
  System.out.println(word[i]);
}
m
o
n
k
e
y
//For Each Loop
char[] word = {'m', 'o', 'n', 'k', 'e', 'y'};
  
for (char letter: word) {
  System.out.println(letter);
}
m
o
n
k
e
y

Both lines of codes yield the same results but the for-each loop is obviously much simpiler and easier to understand.

For each iteration, the for-each loop takes each element of the collection and stores it in a loop variable. Thus, it executes the code written in the body of the loop for each element of the array or collection.

Most importantly, the traversal happens until the last element of the array or collection. No indexing is involved

Pros:

  • makes code easier to read and understand
  • eliminates possible coding mistakes

Cons:

  • 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.
  • limited variability to the collection
  • situational

Hacks

Could I use a for-each loop to print out 4 of the 5 elements of an array only?

Write a for-each loop that adds up all the values of the array (sum):

int numbers[] = {2, 5, 7, 12}

and print the results

Final Hacks/HOMEWORK

Try to write a caesar cipher program that shifts each letter in a message 3 letters forward. Use any of the methods you learned today. Use it to decode the 3 messages we've given you!

public class CaesarCipher {

    public static void main(String[] args) {

        String[] letters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"};
        String message1 = "Kfzb gly!";
        String message2 = "zlab zlab zlab";
        String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";

    }
}