CSA Blog

Ian Wu

Unit 4.4 - Nested Iteration

4.1 While Loop 4.2 For Loop 4.3 String Iteration 4.4 Nested Iteration Unit 4 HW Quiz

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: \n");
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 5 
1 2 3 4 
1 2 3 
1 2 

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

Answer here + One sentence Explanation

Screenshot 2024-09-29 at 15 54 38

Answer here + One sentence Explanation

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

Diamond Pattern:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

Magic Square (Latin Square):
9	15	1	7	
14	4	6	12	
3	5	11	13	
8	10	16	2	

Prime Number Spiral:
0	2	3	0	5	
0	17	0	19	0	
0	0	0	0	7	
0	23	0	0	0	
13	0	11	0	0	
2
15


Iteration: 0

Current Velocity: 2, 2

Unit 4.3 - String Iteration

4.1 While Loop 4.2 For Loop 4.3 String Iteration 4.4 Nested Iteration Unit 4 HW Quiz

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

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

Popcorn Hack:

Iterate through the characters a string with a while loop

String string = "qwertyuioplkjhgfdsazxcvbnm";

int i = 0;
while (i < string.length()) {
    System.out.println(string.charAt(i));
    i += 1;
}
q
w
e
r
t
y
u
i
o
p
l
k
j
h
g
f
d
s
a
z
x
c
v
b
n
m

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

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 encryptedPhrase = new StringBuilder();
        for (char letter : this.phrase.toCharArray()) {
            if (Character.isLetter(letter)) {
                char base = Character.isUpperCase(letter) ? 'A' : 'a';
                char shiftedLetter = (char) ((letter - base + this.key) % 26 + base);
                encryptedPhrase.append(shiftedLetter);
            } else {
                encryptedPhrase.append(letter);
            }
        }
        return encryptedPhrase.toString();
    }
}

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

System.out.println("test 1: " + test1.encrypt());
System.out.println("test 2: " + test2.encrypt());
System.out.println("test 3: " + test3.encrypt());
test 1: khoor zruog
test 2: klmnopq
test 3: c fipy wmu
2
15


Iteration: 0

Current Velocity: 2, 2