Unit 4.1

Popcorn Hack 1

int i = 0;
while (i < 5) {
    System.out.println(i);
}
int i = 0;
while (i < 5) {
    System.out.println(i);
    i++;  // Increment i by 1
}

0
1
2
3
4

Increment Statement (i++): This line increments the value of i by 1 during each iteration of the loop. Without this increment, the condition i < 5 would always evaluate to true, resulting in an infinite loop.

Unit 4.2

Hack

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        // Initialize the list of numbers
        int[] intList = {0, 4, 51, 83, 92, 10, 123, 145};

        // Create lists to hold even and odd numbers
        List<Integer> evenList = new ArrayList<>();
        List<Integer> oddList = new ArrayList<>();

        // Using a for loop to iterate through intList
        for (int i = 0; i < intList.length; i++) {
            if (intList[i] % 2 == 0) {
                evenList.add(intList[i]);  // Add to even list
            } else {
                oddList.add(intList[i]);    // Add to odd list
            }
        }

        // Using a for-each loop to iterate through intList
        for (int number : intList) {
            if (number % 2 == 0) {
                evenList.add(number);  // Add to even list
            } else {
                oddList.add(number);    // Add to odd list
            }
        }

        // Output the even and odd lists
        System.out.println("Even numbers: " + evenList);
        System.out.println("Odd numbers: " + oddList);
    }
}

Main.main(null);
Even numbers: [0, 4, 92, 10, 0, 4, 92, 10]
Odd numbers: [51, 83, 123, 145, 51, 83, 123, 145]

Unit 4.3

Popcorn Hack

Iterate through the characters a string with a while loop.

HW

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

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

    public String encrypt() {
        // your code here

        return null; // return encrypted phrase here
    }
}

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

        // Iterate through each character in the phrase
        for (char ch : phrase.toCharArray()) {
            // Check if the character is a letter
            if (Character.isLetter(ch)) {
                // Determine the base (for 'A' or 'a')
                char base = Character.isUpperCase(ch) ? 'A' : 'a';
                // Shift the character by the key, wrapping around if necessary
                char encryptedChar = (char) ((ch - base + key) % 26 + base);
                encryptedPhrase.append(encryptedChar);
            } else {
                // If it's not a letter, keep it as is (e.g., spaces and punctuation)
                encryptedPhrase.append(ch);
            }
        }

        return encryptedPhrase.toString(); // return encrypted phrase here
    }

    public static void main(String[] args) {
        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()); // Output: khoor zruog
        System.out.println("test 2: " + test2.encrypt()); // Output: klmnopqrstu
        System.out.println("test 3: " + test3.encrypt()); // Output: i zayx uqe
    }
}

CaesarCipher.main(null);
test 1: khoor zruog
test 2: klmnopq
test 3: c fipy wmu

Unit 4.4

Hack

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter the number of rows: \n");
        int rows = scanner.nextInt();
        
        // Corrected loop condition and decrement operator
        for (int i = rows; i >= 1; i--) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
        
        scanner.close();
    }
}

Main.main(null);
Enter the number of rows: 
1 2 3 4 
1 2 3 
1 2 
1 
  1. public class Main: Added a class declaration to contain the main method.
  2. public static void main(String[] args): Wrapped the code in the main method for proper execution.
  3. i--: Changed from i- to i-- to correctly decrement the loop variable.
  4. Loop Condition: Changed i > 1 to i >= 1 to ensure that the loop includes the case where i equals 1, allowing it to print the first row.

Answer here + One sentence Explanation

for (int i = 2; i < 8; i++) {
    for (int y = 1; y <= 5; y++) {
        System.out.print("*");
    }
    System.out.println();
}
*****
*****
*****
*****
*****
*****

The code will print a rectangle of asterisks, with 6 rows and 5 columns.

  • The outer loop (for (int i = 2; i < 8; i++)) iterates 6 times (from 2 to 7, inclusive), and for each iteration, the inner loop (for (int y = 1; y <= 5; y++)) prints 5 asterisks on the same line, followed by a line break after each row.

HW

1

What does the following code print? 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. 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

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

Answer: D

The loop starts with i = 3 and continues until i reaches 12 (inclusive). Therefore, it prints every integer from 3 to 12, resulting in the output 3 4 5 6 7 8 9 10 11 12. In a for loop, the variable (e.g., i) is typically initialized and controlled by the loop itself. Its scope is limited to the loop, making it easy to manage and avoid conflicts with other variables in the program. In contrast, a while loop may utilize an existing variable that persists outside of its scope, which can lead to unintentional side effects if that variable is modified elsewhere in the code. This can make it harder to debug and understand the control flow of the program.

2

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

A. 9 B. 7 C. 8 D. 6

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

Answer: B The loop starts at i = 3 and continues until i is less than 11. The values of i during the iterations are: 3, 4, 5, 6, 7, 8, 9, 10. Thus, it prints asterisks 8 times in total.

3

A. -4 -3 -2 -1 0 B. -5 -4 -3 -2 -1 C. 5 4 3 2 1

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

Answer: B.

The loop starts with x = -5 and increments x by 1 during each iteration, printing the value of x before the increment. The output will thus be -4 -3 -2 -1 0, but since 0 is not less than 0, the last increment will not print. Therefore, the correct output is -4 -3 -2 -1.

4

A. 20 B. 21 C. 25 D. 30

int sum = 0;

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

System.out.println(sum);

The loop runs from 1 to 5, calculating the sum based on whether i is odd or even:

  • For i = 1: sum = 0 + 1 = 1
  • For i = 2: sum = 1 + (2 * 2) = 5
  • For i = 3: sum = 5 + 3 = 8
  • For i = 4: sum = 8 + (4 * 2) = 16
  • For i = 5: sum = 16 + 5 = 21

Thus, the final output is 21.

Loops 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
import java.util.ArrayList;
import java.util.List;

public class DivisibleNumbers {
    public static void main(String[] args) {
        List<Integer> divisibleNumbers = new ArrayList<>();
        int i = 1;

        while (i <= 50) {
            if (i % 3 == 0 || i % 5 == 0) {
                divisibleNumbers.add(i);
            }
            i++;
        }

        System.out.println("Numbers divisible by 3 or 5 (while loop): " + divisibleNumbers);
    }
}

DivisibleNumbers.main(null);
Numbers divisible by 3 or 5 (while loop): [3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50]

For Loop

import java.util.ArrayList;
import java.util.List;

public class DivisibleNumbers {
    public static void main(String[] args) {
        List<Integer> divisibleNumbers = new ArrayList<>();

        for (int i = 1; i <= 50; i++) {
            if (i % 3 == 0 || i % 5 == 0) {
                divisibleNumbers.add(i);
            }
        }

        System.out.println("Numbers divisible by 3 or 5 (for loop): " + divisibleNumbers);
    }
}

DivisibleNumbers.main(null);
Numbers divisible by 3 or 5 (for loop): [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

import java.util.ArrayList;
import java.util.List;

public class PalindromeFinder {
    public static void main(String[] args) {
        List<Integer> testList = List.of(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);
        List<Integer> palindromes = new ArrayList<>();

        int index = 0;
        while (index < testList.size()) {
            int number = testList.get(index);
            if (isPalindrome(number)) {
                palindromes.add(number);
            }
            index++;
        }

        System.out.println("Palindromes: " + palindromes);
    }

    private static boolean isPalindrome(int number) {
        String str = Integer.toString(number);
        String reversedStr = new StringBuilder(str).reverse().toString();
        return str.equals(reversedStr);
    }
}

PalindromeFinder.main(null);
Palindromes: [4444, 515, 2882, 6556, 595]

Bonus

import java.util.Arrays;

public class SpiralMatrix {
    public static void main(String[] args) {
        int n = 3; // Example size
        int[][] matrix = new int[n][n];
        int value = 1;
        int top = 0, bottom = n - 1, left = 0, right = n - 1;

        while (value <= n * n) {
            for (int i = left; i <= right; i++) {
                matrix[top][i] = value++;
            }
            top++;

            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = value++;
            }
            right--;

            for (int i = right; i >= left; i--) {
                matrix[bottom][i] = value++;
            }
            bottom--;

            for (int i = bottom; i >= top; i--) {
                matrix[i][left] = value++;
            }
            left++;
        }

        System.out.println("Spiral Matrix:");
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}

SpiralMatrix.main(null);

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