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 would be D as 3 is the starting index of the variable in the for loop. The loop increases until it is less than equal to 12, meaning the last number printed must be 12.

This gives the answer of D as 3 is the first number and 12 is the last number.

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

Inside the for loop, i is stuck inside the scope of the for loop and cant be accessed outside of it. Using an already existing variable means it can be accessed outside of the 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("*");
}

The answer is C as the starting index is 3, and because the last index is less than 11. This means that the loop will run (11-3) times, for 8 times. If the last value were to be less than or equal to, that would be 9 times.

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

The answer would be A because it starts at -4 because x is increased before printing. This means the last number will also 0. The loop will run 5 times before it reaches 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);

The answer is B as it is adding the current index multiplied by 2 when it is even, and just adding when it is odd. Given this patttern that ranges from 1 to 5 (inclusive), it can be caclulated to be 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
import java.util.ArrayList;

ArrayList<Integer> divisibleList = new ArrayList<Integer>();

int j = 1;

while(j <= 50)
{
    if(j % 3 ==0 || j % 5==0)
    {
        divisibleList.add(j);
    }
    j++;
}
System.out.println(divisibleList);
divisibleList.clear();

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

System.out.println(divisibleList);
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50]
[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

int[] testArray = {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<testArray.length)
{
    String str = Integer.toString(testArray[i]);
    StringBuilder toCheck = new StringBuilder();
    toCheck.append(str);
    toCheck.reverse();
    if(str.equals(toCheck.toString()))
    {
        System.out.println(testArray[i]);
    }
    i++;
}
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]]

 int n = 5;

        int[][] spiral = new int[n][n];
        int value = 1; 

        int minCol = 0, maxCol = n - 1;
        int minRow = 0, maxRow = n - 1;

        while (minCol <= maxCol && minRow <= maxRow) {
            
            //top row
            for (int i = minCol; i <= maxCol; i++) {
                spiral[minRow][i] = value++;
            }
            minRow++;  

            //right column
            for (int i = minRow; i <= maxRow; i++) {
                spiral[i][maxCol] = value++;
            }
            maxCol--;  

            // bottom right to left
            if (minRow <= maxRow) {
                for (int i = maxCol; i >= minCol; i--) {
                    spiral[maxRow][i] = value++;
                }
                maxRow--;  //move up from bottom
            }

            // left column
            if (minCol <= maxCol) {
                for (int i = maxRow; i >= minRow; i--) {
                    spiral[i][minCol] = value++;
                }
                minCol++;  //loop
            }
        }

        for (int[] row : spiral) {
            for (int element : row) {
                System.out.print(element + "\t");
            }
            System.out.println();
        }
1	2	3	4	5	
16	17	18	19	6	
15	24	25	20	7	
14	23	22	21	8	
13	12	11	10	9