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) {
    ...
}
|       ...
illegal start of expression

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: 

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) {

    int profit = 5450000;
    int i = 0;

        while( profit < 30000000) {
            profit += profit * (1 + 0.05 * i);
            i++;

        }
        System.out.println(i);

    }
}

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) {
        for (int x = 10; x <= 15; x++) {
            System.out.println(x);
        }

    }
}

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();
}
****
****
****
****
****

For Each 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

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};

int sum = 9;
for (int num: numbers) {
    sum += num;
}

System.out.println(sum);
35

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 {

        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[] capitalLetters = {"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"};
        
        static String message1 = "Kfzb gly!";
        static String message2 = "zlab zlab zlab";
        static String message3 = "prmbozxifcoxdfifpqfzbumfxifalzflrp";
 
        public static void main(String[] args) {  
        CaesarCipher decode = new CaesarCipher(message1); 
        CaesarCipher decode2 = new CaesarCipher(message2); 
        CaesarCipher decode3 = new CaesarCipher(message3); 
        
        }

    String decodeMessage = "";

    public CaesarCipher(String message) {
   
        for (int i=0; i < message.length(); i++){
            decodeMessage = message.substring(i, i+1);
            if (decodeMessage.equals(" ")) {
                System.out.print(" "); 
            }
            if (decodeMessage.equals("!")) {
                System.out.print("!"); 
            }
            for (int j = 0; j < letters.length; j++) {
                if (decodeMessage.equals(letters[j])) {
                    System.out.print(letters[(j+3)%26]); 
                }

                if (decodeMessage.equals(capitalLetters[j])) {
                    System.out.print(capitalLetters[(j+3)%26]); 
                }
            }
    }
    System.out.println(""); 
 }

}

CaesarCipher.main(null);
Nice job!
code code code
supercalifragilisticexpialidocious