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)

Answer: D The interating variable of the for loop starts at 3 and increases by 1 until the variable is equal to 12. Each time the number increases, it is printed out to the terminal starting with the original number, 3. Thus, it will print every number from 3-12. Answer is D.

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

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

In a for loop, the variable (like i) is typically declared within the loop, is automatically managed, and only exists during the loop’s execution. A while loop, however, uses a variable that is declared and updated outside the loop, giving you more manual control and allowing the variable to persist beyond the loop’s scope.

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)

Answer: C. The interating variable of the for loop starts at 3 and increases by 1 while the number is less than 11. Each time the number increases, an * is printed out to the terminal. Thus the * will be printed out 8 times because 11 - 3 = 8.

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

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)

Answer: A. The integer x=-5 is declared outside the while loop and the while loop only persists while the integer is less than 0. The integer is incremented before the print statement so -4 is the first number printed not -5. This will continue until x=0.

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

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)

Answer: B. The interating variable begins at 1 and increments by 1 everytime the for loop is ran until the interating varaiable is equal to 5. This means the loop will go through the numbers 1, 2, 3, 4, 5. The rule states that if a number is even, that number will be multipied by two and added to the sum. For odd numbers the original number will be added to the sum with no manipulations. Thus the sum is equal 1 + 3 + 5 + (2 x 2) + (4 x 2), since even numbers should be multiplied by 2 before being added to the sum. Thus the program will evaluate the expression I listed which is equal to 21.

int sum = 0;

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

System.out.println(sum);

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
//Lists for numbers that are divisible by 5 and 3 respectively 
List<Integer> divisibleByThree = new ArrayList<>();
List<Integer> divisibleByFive = new ArrayList<>();

//Iterating Variable
int x = 1;

//while loop
while (x <= 50) {
    //Edge case for numbers divisble by both
    if (x % 5 == 0 && x % 3 ==0) {
        divisibleByThree.add(x);
        divisibleByFive.add(x);
    } else if (x % 5 == 0) {
        divisibleByFive.add(x);
    } else if (x % 3 ==0) {
        divisibleByThree.add(x);
    }
    x++;
}

//Output
System.out.println("Numbers divisble by 3 From 1-50:" + divisibleByThree);
System.out.println("Numbers divisble by 5 From 1-50: " + divisibleByFive);
Numbers divisble by 3 From 1-50:[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]
Numbers divisble by 5 From 1-50: [5, 10, 15, 20, 25, 30, 35, 40, 45, 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

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

for (int i = 0; i < test_list.length; i++) {
    int number = test_list[i];
    int original = number;
    int reversed = 0;
    
    // Reverse the number
    while (number != 0) {
        int digit = number % 10;
        reversed = reversed * 10 + digit;
        number /= 10;
    }
    
    // If the original number is the same as the reversed, print it
    if (original == reversed) {
        System.out.println(original);
    }
}

4444
515
2882
6556
595

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

// Import necessary packages
import java.util.Arrays;

public class SpiralMatrix {
    public static void main(String[] args) {
        int n=3;
        int[][] matrix = generateSpiralMatrix(n);
        printMatrix(matrix);
    }

    public static int[][] generateSpiralMatrix(int n) {
        int[][] matrix = new int[n][n];
        int num = 1;
        int top = 0, bottom = n - 1;
        int left = 0, right = n - 1;

        while (top <= bottom && left <= right) {
            for (int i = left; i <= right; i++) {
                matrix[top][i] = num++;
            }
            top++;
            for (int i = top; i <= bottom; i++) {
                matrix[i][right] = num++;
            }
            right--;
            for (int i = right; i >= left; i--) {
                matrix[bottom][i] = num++;
            }
            bottom--;
            for (int i = bottom; i >= top; i--) {
                matrix[i][left] = num++;
            }
            left++;
        }

        return matrix;
    }

    public static void printMatrix(int[][] matrix) {
        for (int[] row : matrix) {
            System.out.println(Arrays.toString(row));
        }
    }
}

// Call the main method to execute the code
SpiralMatrix.main(null);
[1, 2, 3]
[8, 9, 4]
[7, 6, 5]