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)

D. i starts out at 3, and is printed out, and then is incremented and printed until it is above 12, in which case the loop terminates, leaving us with

print 3 -> increment -> print 4 -> increment…. -> print 12 -> increment -> i = 13, condition not fulfilled because 13 > 12, loop terminates

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

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)

C. Since the condition is not inclusive, we can simply subtract the number being compared to in the condition from the initial value. 11-3 = 8, and * is printed once per loop, meaning it should print out 8 times total. Once it loops the 8th time, i will increment to be = to 11, and since 11 is not < 11, the condition is no longer fulfilled, and the loop terminates.

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)

A. Because x increments before printing, it will not start out printing -5, which is the initial value of x, but will start by printing x + 1, which would be -4. It goes on to iterate until x is -1, where x is incremented and printed one more time. Now that x = 0, and 0 is not < 0, the loop terminates, leaving us with -4 -3 -2 -1 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)

1+4+3+8+5 = 21

The remainder of 1/2 or 1 mod 2 is not equal to 0, so the value is added to sum

The remainder of 2/2 or 2 mod 2 is equal to 0, so the value is doubled and added to sum

Every even number will be doubled then added, while every odd number will be simply added.

Because we are looping a total of 5 times, (number in condition = 5, initial value = 1, 5-1=4, but because it is inclusive, we add 1 back, so loops 5 times) and the loop terminates after i is greater than 5, all the numbers from the initial value of 1 to the ending value of 5 must be considered for this. Doing some simple math, knowing that every even number up to 5 will be doubled and every odd one won’t, we arrive at 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
import java.util.ArrayList;
import java.util.List;

List<Integer> whileloop = new ArrayList<>();
int i = 1;
while (i <= 50) {
    if (i % 3 == 0 || i % 5 == 0) {
        whileloop.add(i);
    }
    i++;
}
System.out.println(whileloop)
[3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50]
import java.util.ArrayList;
import java.util.List;

List<Integer> forloop = new ArrayList<>();
for (int i = 1; i <= 50; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
        forloop.add(i);
    }
}
System.out.println(forloop)
[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;


List<Integer> palindromes = new ArrayList<>();

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

int i = 0;
while (i < test_list.length) {
    String value = Integer.toString(test_list[i]);
    StringBuilder newString = new StringBuilder();
    
    for (int j = value.length() - 1; j >= 0; j--) {
        newString.append(value.charAt(j)); 
    }

    if (newString.toString().equals(value)) {
        palindromes.add(test_list[i]); 
    }
    
    i++;
}


System.out.println("all palindromes: " + palindromes);


all palindromes: [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]]

easier to see (same code as below)

int n = 3; //dimensions of matrix for x and y axis
int[][] spiral = new int[n][n]; //initialize the matrix with dimensions of n by n, making it a square
int left = 0; //left border
int right = n - 1; // right border
int top = 0; //top border
int bottom = n - 1; // bottom border
int num = 1; //starting value for both the matrix and the loop
//loop until num is larger than the area of the matrix
//since the area of the matrix is basically the numbers that need to be filled in, we also use num to fill the numbers in
while (num <= n*n) { //visualize setting matrix values as a "turtle" starting at 0,0
    for (int i = left; i <= right; i++) { // 1st loop: set values in the first row in increasing order until i reaches right border, ends at [0][2]
        spiral[top][i] = num;
        num++; //use num++ for reasons stated above, increase num every time to both fill the numbers in and act as a limit for the loop
    //2nd loop: now the right, left, top, and bottom borders are in the center
    } //2nd loop: stay on the top border which is at the center, and set values until you hit the right border, which is at the center
    // 2nd loop: now, because all the borders have successfully closed in, and the "turtle" has kind of followed the borders until they close in on each other
    // 2nd loop: the matrix is filled, num has been incremented enough to be 1 greater than the area of the matrix, so the loop terminates
    // beyond: for bigger arrays, the turtle follows the same pattern, and the borders close in on each other once again after values are filled in,
    // beyond:  but just with more iterations of this pattern, and the if statements will execute more than once as the conditions won't be fulfilled until later
    top++; // add 1 to top to move "turtle"/upper bound downward 1
    // give up on the turtle analogy and move back to borders
    for (int i = top; i <= bottom; i++) {
        spiral[i][right] = num; //stay on the right border and move down rows by incrementing i until you hit the bottom border
        num++;
    } //now end at [2][2]
    right--;
    //move the right border in 1 so you don't overwrite values you already put in
    if (top <= bottom) { // check if the top border is still less than (higher than) the bottom border, if so proceed
        for (int i = right; i >= left; i--) { // start on the newly defined right border (1 in from the original one) on the bottom row
            spiral[bottom][i] = num; // stay on the bottom border and move leftward, completing the bottom row
            num++;
        }
        bottom--; //close in the bottom border so it is in the center of the array, no more moving vertically
    }

    if (left <= right) { // make sure left border is less than (more leftward than) the right border
        for (int i = bottom; i >= top; i--) { 
            spiral[i][left] = num; //stay on the left border which is still at 0, and move upward until you hit the top border
            num++;
        }
        left++; //close in the left border so that it is in the center of the array, only 1 place left to go
    }
}

System.out.println(Arrays.deepToString(spiral)); //print matrix unformatted

for (int row = 0; row < n; row++) { 
    for (int col = 0; col < n; col++) { 
        System.out.print(spiral[row][col] + " "); //print matrix by row so it is easier to visualize
    }
    System.out.println();
}

int n = 3; //dimensions of matrix for x and y axis
int[][] spiral = new int[n][n]; //initialize the matrix with dimensions of n by n, making it a square
int left = 0; //left border
int right = n - 1; // right border
int top = 0; //top border
int bottom = n - 1; // bottom border
int num = 1; //starting value for both the matrix and the loop
//loop until num is larger than the area of the matrix
//since the area of the matrix is basically the numbers that need to be filled in, we also use num to fill the numbers in
while (num <= n*n) { //visualize setting matrix values as a "turtle" starting at 0,0
    for (int i = left; i <= right; i++) { // 1st loop: set values in the first row in increasing order until i reaches right border, ends at [0][2]
        spiral[top][i] = num;
        num++; //use num++ for reasons stated above, increase num every time to both fill the numbers in and act as a limit for the loop
    //2nd loop: now the right, left, top, and bottom borders are in the center
    } //2nd loop: stay on the top border which is at the center, and set values until you hit the right border, which is at the center
    // 2nd loop: now, because all the borders have successfully closed in, and the "turtle" has kind of followed the borders until they close in on each other
    // 2nd loop: the matrix is filled, num has been incremented enough to be 1 greater than the area of the matrix, so the loop terminates
    // beyond: for bigger arrays, the turtle follows the same pattern, and the borders close in on each other once again after values are filled in,
    // beyond:  but just with more iterations of this pattern, and the if statements will execute more than once as the conditions won't be fulfilled until later
    top++; // add 1 to top to move "turtle"/upper bound downward 1
    // give up on the turtle analogy and move back to borders
    for (int i = top; i <= bottom; i++) {
        spiral[i][right] = num; //stay on the right border and move down rows by incrementing i until you hit the bottom border
        num++;
    } //now end at [2][2]
    right--;
    //move the right border in 1 so you don't overwrite values you already put in
    if (top <= bottom) { // check if the top border is still less than (higher than) the bottom border, if so proceed
        for (int i = right; i >= left; i--) { // start on the newly defined right border (1 in from the original one) on the bottom row
            spiral[bottom][i] = num; // stay on the bottom border and move leftward, completing the bottom row
            num++;
        }
        bottom--; //close in the bottom border so it is in the center of the array, no more moving vertically
    }

    if (left <= right) { // make sure left border is less than (more leftward than) the right border
        for (int i = bottom; i >= top; i--) { 
            spiral[i][left] = num; //stay on the left border which is still at 0, and move upward until you hit the top border
            num++;
        }
        left++; //close in the left border so that it is in the center of the array, only 1 place left to go
    }
}

System.out.println(Arrays.deepToString(spiral)); //print matrix unformatted

for (int row = 0; row < n; row++) { 
    for (int col = 0; col < n; col++) { 
        System.out.print(spiral[row][col] + " "); //print matrix by row so it is easier to visualize
    }
    System.out.println();
}

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