Skip to the content.
4.1 While Loop 4.2 For Loop 4.3 String Iteration 4.4 Nested Iteration Unit 4 HW Quiz

Unit 4 - Iteration P1

AP CSA

Collegeboard Resources for loops/iteration

## AP Computer Science A - Unit 4 Home Page

Welcome to Unit 4! In this unit, we will explore various concepts of Iteration in Java, focusing on while, for, for each, do while loops and string manipulation

Learning Goals:

  • Understand how to declare, initialize, loops
  • Learn how to iterate through strings
  • Practice writing algorithms that use iteration

Key Topics:

Topic 4.1 - while Loops Topic 4.2 - for Loops Topic 4.3 - Developing Algorithms Using Strings Topic 4.4 - Nested Iteration

4.1 While Loops

While loops run until the given condition is false. Format of loop below.

int index = 0; // iterating value
while (index < 5) { // condition, if this is false, the loop terminates
    System.out.println(index); // body code
    index++; // iterates the iterating value
}
0
1
2
3
4
# Python Version
i=0
while (i<5):
    print(i)
    i+=1
|   # Python Version

illegal character: '#'



|   i=0

';' expected

Explanation

  • in the above while loop:
    • index is the incrementing variable
    • index < 5 is the condition (once index < 5 is false, this loop breaks)
    • System.out.println(i); is the body code that runs every time the loop iterates
    • index++; is incrementing the incrementing variable

Do While Loops:

  • This type of while loop runs the block inside the do{} statement once, then iterates through the loop
  • this ensures that the code runs at least once

Example of Do While loop below

int i = 0; // iterating value
do { // this makes sure the code runs at least once
    System.out.println(i); // body code
    i++; // iterates the iterating value
} while (i < 5); // condition, if this is false, loop terminates

Explanation:

  • in the above loop:
    • code inside of the do{} statement runs at least once, then keeps on running as long as the condition, i<5, is true.
    • similarly to the normal while loop, there is body code, and there is an incrementing variable

IMPORTANT:

  • While loops to not have to have an incrementing variable, for example, you can have a loop that iterates as long as there are items present in a list
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.add(40);

System.out.println(list + " before loop!!");
while (!list.isEmpty()) {
    System.out.println("Element: " + list.remove(0));
}
System.out.println(list + " after loop!!");

Fun While Loop Hack:

  • find and fix the missing increment in the while loop
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;
}
0
1
2
3
4

4.2 For Loops

Similar to while loops, for loops run until a condition is false. Format of for loop below:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

Explanation

  • in the above for loop:
    • int i = 0 defines the iterating variable
    • i < 5 is the condition (once i < 5 is false, this loop breaks)
    • i++ is the incrementation of the iterating variable
    • System.out.println(i); is the body code that runs every time the loop iterates

For Each Loops:

  • Apart from iterating using an incrementing variable, you can also iterate through items in a list.

    Example of For Each loop below

int[] list = {1, 2, 3, 4, 5}; // any list
for (int item : list) { // for each item in the list, execute the body
    System.out.println(item); // body code
}
#python version
array=[1, 2, 3, 4, 5]
for i in array:
    print(i)

Explanation:

  • in the above loop:
    • int item : list - this line is saying that for each item in the list, execute code below
    • System.out.println(num); - this line is the body code.

Fun For Loop Hack:

Create a program that iterates through a list of numbers (int_list = {0, 4, 51, 83, 92, 10, 123, 145}) using both a for loop and a for each loop, then split the numbers in the list into even/odd lists, and output them.

4.3 String Iteration

simple for loop to iterate through every character using index with charAt():

String word = "hello";
for (int i = 0; i < word.length(); i++) {
    System.out.println(word.charAt(i));
}
h
e
l
l
o

in order to use an enhanced for loop, a character array is needed.
toCharArray() can help accomplish this.
example of iteration with an enhanced for loop:

String word = "hello";
for (char c : word.toCharArray()) {
    System.out.println(c);
}
h
e
l
l
o

Popcorn Hack:

Iterate through the characters a string with a while loop

public class PopcornHack1 {
    public static void main(String[] args) {
        String word = "hello";
        int i = 0;

        while (i < word.length()) {
            System.out.println(word.charAt(i));
            i++;
        }
    }
}

What is a substring?

  • a substring is a subset of the main string
  • the substring(a,b) method creates a substring with the characters of the original string with indices of a to b.
  • string.length() returns the length of the string
  • string1.equals(string2) determines if the two strings have the same characters
String word = "sunflower";
String sub = "low";
boolean found = false;
for (int i = 0; i < word.length(); i++) {
    String portion = word.substring(i, i+sub.length());
    if (portion.equals(sub)){
        found = true;
    }
}

System.out.println("is " + )

Iterating through words

use split() to split a string into an array.
then we can iterate through the array to access each individual word

String phrase = "this is a string";
String[] words = phrase.split(" ");
for (String word : words) {
    System.out.println(word);
}
this
is
a
string

Homework Hack!

code a caesar cipher that will encrypt any string with any key provided.
your code should go into the encrypt() method, and should successfully pass the test cases provided
as a bonus, try to use StringBuilder

public class CaesarCipher {
    private int key;
    private String phrase;

    public CaesarCipher(int key, String phrase) {
        this.key = key;
        this.phrase = phrase;
    }

    public String encrypt() {
        StringBuilder encrypted = new StringBuilder(); // Using StringBuilder for efficient string manipulation
        int shift = key % 26; // To handle shifts greater than 26

        // Loop through each character of the phrase
        for (char c : phrase.toCharArray()) {
            if (Character.isLetter(c)) { // Check if the character is a letter
                char base = Character.isUpperCase(c) ? 'A' : 'a'; // Determine if it's uppercase or lowercase
                char shifted = (char) ((c - base + shift) % 26 + base); // Shift the letter and wrap within alphabet
                encrypted.append(shifted); // Append the shifted character to the result
            } else {
                encrypted.append(c); // Preserve non-letter characters (spaces, punctuation, etc.)
            }
        }

        return encrypted.toString(); // Return the encrypted string
    }

    public static void main(String[] args) {
        System.out.println("Starting tests..."); // Check if the program is running

        // Test cases
        CaesarCipher test1 = new CaesarCipher(3, "hello world");
        CaesarCipher test2 = new CaesarCipher(10, "abcdefg");
        CaesarCipher test3 = new CaesarCipher(20, "i love csa");

        // Print the results of encryption
        System.out.println("Test 1: " + test1.encrypt()); // Expected: khoor zruog
        System.out.println("Test 2: " + test2.encrypt()); // Expected: klmnopqrst
        System.out.println("Test 3: " + test3.encrypt()); // Expected: c fspi wmu
    }
}

4.4 Nested Iteration

How to iterate through with a time complexity of O(n^2)

for (int i = 1; i <= 3; i++) { // Outer loop
    System.out.println("Outer loop iteration: " + i);
    for (int j = 1; j <= 3; j++) { // Inner loop
        System.out.println("    Inner loop iteration: " + j);
        }
    }
Outer loop iteration: 1
    Inner loop iteration: 1
    Inner loop iteration: 2
    Inner loop iteration: 3
Outer loop iteration: 2
    Inner loop iteration: 1
    Inner loop iteration: 2
    Inner loop iteration: 3
Outer loop iteration: 3
    Inner loop iteration: 1
    Inner loop iteration: 2
    Inner loop iteration: 3

What is wrong with this code cell(Hack)

//Hint: Check the Syntax and look at the equals to signs on the example above

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
for (int i = rows; i>=1; i--) {
    for (int j = 1; j <= i; j++) {
        System.out.print(j + " ");
    }
    System.out.println();
    }
        
scanner.close();
Enter the number of rows: 1 2 3 4 
1 2 3 
1 2 
1 

Sample input: 5

Sample Output 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1

Screenshot 2024-09-19 at 20 45 04

Ans: B, 4*5=20. this is because 8-3=5, so the first loop will run 5 times, and the nested loop will run 4 times because 5-1.

Answer here + One sentence Explanation

Screenshot 2024-09-29 at 15 54 38

Ans: 24, 8-2=6 and 5-1=4. 6*4=24

Video To watch later if you need more help

Cool Usecase of nested loops


    // Define the dimensions
    int rows = 5;

    // First loop to generate a diamond pattern
    System.out.println("Diamond Pattern:");
    for (int i = 1; i <= rows; i++) {
        // Print spaces for left alignment
        for (int j = i; j < rows; j++) {
            System.out.print(" ");
        }
        // Print asterisks for the upper part of the diamond
        for (int k = 1; k <= (2 * i - 1); k++) {
            System.out.print("*");
        }
        System.out.println();
    }
    for (int i = rows - 1; i >= 1; i--) {
        // Print spaces for right alignment
        for (int j = rows; j > i; j--) {
            System.out.print(" ");
        }
        // Print asterisks for the lower part of the diamond
        for (int k = 1; k <= (2 * i - 1); k++) {
            System.out.print("*");
        }
        System.out.println();
    }

    // Second loop: Magic Square (Latin Square)
    System.out.println("\nMagic Square (Latin Square):");
    int size = 4;
    int[][] magicSquare = new int[size][size];
    int num = 1, row = 0, col = size / 2;

    while (num <= size * size) {
        magicSquare[row][col] = num;
        num++;
        int newRow = (row - 1 + size) % size;
        int newCol = (col + 1) % size;

        if (magicSquare[newRow][newCol] != 0) {
            row = (row + 1) % size;
        } else {
            row = newRow;
            col = newCol;
        }
    }

    // Print the magic square
    for (int[] r : magicSquare) {
        for (int c : r) {
            System.out.print(c + "\t");
        }
        System.out.println();
    }
    
    // Third loop: Prime Number Spiral
    System.out.println("\nPrime Number Spiral:");
    int spiralSize = 5;
    int[][] spiral = new int[spiralSize][spiralSize];
    int val = 1, startRow = 0, endRow = spiralSize - 1, startCol = 0, endCol = spiralSize - 1;

    while (startRow <= endRow && startCol <= endCol) {
        // Fill top row
        for (int i = startCol; i <= endCol; i++) {
            spiral[startRow][i] = isPrime(val) ? val : 0;
            val++;
        }
        startRow++;

        // Fill right column
        for (int i = startRow; i <= endRow; i++) {
            spiral[i][endCol] = isPrime(val) ? val : 0;
            val++;
        }
        endCol--;

        // Fill bottom row
        if (startRow <= endRow) {
            for (int i = endCol; i >= startCol; i--) {
                spiral[endRow][i] = isPrime(val) ? val : 0;
                val++;
            }
            endRow--;
        }

        // Fill left column
        if (startCol <= endCol) {
            for (int i = endRow; i >= startRow; i--) {
                spiral[i][startCol] = isPrime(val) ? val : 0;
                val++;
            }
            startCol++;
        }
    }

    // Print the spiral
    for (int[] r : spiral) {
        for (int c : r) {
            System.out.print(c + "\t");
        }
        System.out.println();
    }


// Method to check if a number is prime
static boolean isPrime(int num) {
    if (num <= 1) return false;
    for (int i = 2; i <= Math.sqrt(num); i++) {
        if (num % i == 0) return false;
    }
    return true;
}

Unit 4 - Iteration: HW

  • This is the homework quiz for unit 4, iterations
  • 4 multiple choice questions
  • 2 programming hacks
  • 1 bonus programming hack (required to get above 0.9)

Question 1:

What does the following code print?

A. 5 6 7 8 9

B. 4 5 6 7 8 9 10 11 12

C. 3 5 7 9 11

D. 3 4 5 6 7 8 9 10 11 12

Click to reveal answer: D

Explain your answer. (explanation is graded not answer)

for (int i = 3; i <= 12; i++) { System.out.print(i + “ “); }

A: The loop iterates from i = 3 to i = 12, and prints each value of i followed by a space.

Bonus:

  • Explain the difference between using a variable like i inside a for loop, vs. using a variable that exists in the code itself for a while loop

A: In a for loop, the variable,i, is only exists during the execution of the loop. A while loop can use any variable, so it’s more flexible but can run forever sometimes

Question 2:

How many times does the following method print a “*” ?

A. 9

B. 7

C. 8

D. 6

Click to reveal answer: C

Explain your answer. (explanation is graded not answer)

for (int i = 3; i < 11; i++) {
    System.out.print("*");
 }

A: The method prints a "*" 8 times. the loop starts at i = 3 and runs while i is less than 11, so 11-3 = 8

Question 3:

What does the following code print?

A. -4 -3 -2 -1 0

B. -5 -4 -3 -2 -1

C. 5 4 3 2 1

Click to reveal answer: A

Explain your answer. (explanation is graded not answer)

int x = -5;
while (x < 0)
{
   x++;
   System.out.print(x + " ");
}

A: The answer is A. The while loop increments x from -5 to 0, printing each value after the increment, so -4, -3, -2, -1, and 0

Question 4:

What does the following code print?

A. 20

B. 21

C. 25

D. 30

Click to reveal answer: B

Explain your answer. (explanation is graded not answer)

int sum = 0;

for (int i = 1; i <= 5; i++) {
    if (i % 2 == 0) {
        sum += i * 2;
    } else {
        sum += i;
    }
}

System.out.println(sum);

A: The answer is B. The loop iterates through 1 to 5, adding each odd number as is and each even number multiplied by 2 to the sum, so 1+4+3+8+5=21.

Loops HW Hack

Easy Hack

  • Use a while loop to find the numbers from 1-50 that are divisible by 3 or 5, then store them into a list (make sure to print it out at the end)
  • Use a for loop to do the same thing detailed above

While

int index = 0;
while (index <= 50) { 
    if (index % 3 == 0 || index % 5 == 0) { 
        System.out.println(index); 
    }
    index++;
}
0
3
5
6
9
10
12
15
18
20
21
24
25
27
30
33
35
36
39
40
42
45
48
50
For
for (int index = 0; index <= 50; index++) {
    if (index % 3 == 0 || index % 5 == 0) { 
        System.out.println(index);
    }
}
0
3
5
6
9
10
12
15
18
20
21
24
25
27
30
33
35
36
39
40
42
45
48
50

Harder Hack

Palindromes are numbers that have the same value when reversed (ex: “123321” or “323”). Create a program that uses a while loop that outputs all palindromes in any given list.

Sample Input: test_list = [5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595]

Sample Output: 4444, 515, 2882, 6556, 595

public class Main {
    public static void main(String[] args) {
        int[] test_list = {5672, 235, 5537, 6032, 317, 8460, 1672, 8104, 7770, 4442, 913, 2508, 1116, 9969, 9091, 522, 8756, 9527, 7968, 1520, 4444, 515, 2882, 6556, 595};
        int i = 0;

        while (i < test_list.length) {
            int num = test_list[i];
            int original = num;
            int reversed = 0;

            // Reverse the digits of the current number
            while (num != 0) {
                int digit = num % 10;
                reversed = reversed * 10 + digit;
                num /= 10;
            }

            // Check if the original number is the same as the reversed number
            if (original == reversed) {
                System.out.print(original + " ");
            }

            i++;
        }
    }
}

Bonus Hack (for above 0.9)

Use a for loop to output a spiral matrix with size n

Example:

Sample Input: n = 3

Output: [[1, 2, 3], [8, 9, 4], [7, 6, 5]]