Skip to the content.
While Loops For Loops Nested Iteration Code Example Hacks Quiz

Unit 4 - HW Quiz

Unit 4 Team Teach HW QUIZ

Unit 4 - Iteration:

  • 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 + " ");
}

The answer is D because the for loop is iterating from the numbers 3 to 12 inclusive and “i” is being post-incremented by 1 each time. Therefore it prints out 3 4 5 6 7 8 9 10 11 12

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

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

C. It prints out 8 stars because i starts from 3 and ends at 10.
10-3+1 = 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. x starts at -5 and ends at -1. Since x is incremented by 1 each iteration, it will print out all the numbers from -5 to -1 inclusive.
So, the output is: -5 -4 -3 -2 -1

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

When i is even, i is doubled and added to the sum.
When i is odd, i is just added to the sum normally.
When i = 1: it’s odd, so sum += 1 → sum = 1.
When i = 2: it’s even, so sum += 2 * 2 → sum = 1 + 4 = 5.
When i = 3: it’s odd, so sum += 3 → sum = 5 + 3 = 8.
When i = 4: it’s even, so sum += 4 * 2 → sum = 8 + 8 = 16.
When i = 5: it’s odd, so sum += 5 → sum = 16 + 5 = 21.
Therefore, the answer is B. 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
// Using while loop:
import java.util.ArrayList;

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

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

        System.out.println("Numbers divisible by 3 or 5 (while loop): " + divisibleBy3Or5);
    }
}
myWhileLoop.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]
// Using a for loop
import java.util.ArrayList;

public class myForLoop {
    public static void main(String[] args) {
        ArrayList<Integer> divisibleBy3Or5 = new ArrayList<>();

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

        System.out.println("Numbers divisible by 3 or 5 (for loop): " + divisibleBy3Or5);
    }
}
myForLoop.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

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

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

public class PalindromeFinder {
    public static void main(String[] args) {
        // Sample Input
        int[] testList = {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 to store palindromes
        List<Integer> palindromes = new ArrayList<>();

        int index = 0;
        while (index < testList.length) {
            if (isPalindrome(testList[index])) {
                palindromes.add(testList[index]);
            }
            index++;
        }

        // Output the result
        System.out.println(palindromes);
    }

    // Function to check if a number is a palindrome
    public static boolean isPalindrome(int num) {
        String strNum = String.valueOf(num);
        String reversedStrNum = new StringBuilder(strNum).reverse().toString();
        return strNum.equals(reversedStrNum);
    }
}

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]]

public class SpiralMatrix {
    public static void main(String[] args) {
        // Sample Input
        int n = 3;

        // Generate the spiral matrix
        int[][] spiralMatrix = generateSpiralMatrix(n);

        // Output the result
        printMatrix(spiralMatrix);
    }

    public static int[][] generateSpiralMatrix(int n) {
        int[][] matrix = new int[n][n]; // Initialize the n x n matrix
        int top = 0, bottom = n - 1, left = 0, right = n - 1; // Boundaries
        int num = 1; // Starting number

        while (top <= bottom && left <= right) {
            // Traverse from left to right
            for (int i = left; i <= right; i++) {
                matrix[top][i] = num++;
            }
            top++; // Move the top boundary down

            // Traverse from top to bottom
            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = num++;
            }
            right--; // Move the right boundary left

            // Traverse from right to left (if applicable)
            if (top <= bottom) {
                for (int i = right; i >= left; i--) {
                    matrix[bottom][i] = num++;
                }
                bottom--; // Move the bottom boundary up
            }

            // Traverse from bottom to top (if applicable)
            if (left <= right) {
                for (int i = bottom; i >= top; i--) {
                    matrix[i][left] = num++;
                }
                left++; // Move the left boundary right
            }
        }
        return matrix;
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            System.out.print("[");
            for (int j = 0; j < row.length; j++) {
                System.out.print(row[j]);
                if (j < row.length - 1) {
                    System.out.print(", ");
                }
            }
            System.out.println("]");
        }
    }
}
SpiralMatrix.main(null);
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]