Unit 4 - Iteration:

  • This assignement will be made of 3 multiple choice questions, and 2 coding hacks.

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 Answer: D

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

Question 2:

How many times does the following method print a *? A. 9 B. 7 C. 6 D. 10 Answer: C

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

Question 3:

What does the following code print? A. 5 4 3 2 1 B. -5 -4 -3 -2 -1 C. -4 -3 -2 -1 0 Answer: C

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

Loops homework 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

Coding Hack(For above 0.9):

Use a for loop to output a spiral matrix with size n

For example: Sample Input: 3

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

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