6.2. Assessment: Writing Loops¶
Subgoals for Writing a Loop
Determine purpose of loop
Pick a loop structure (while, for, do_while)
Define and initialize variables
Determine termination condition
Invert termination condition to continuation condition
Write the loop body
Update Loop Control Variable to reach termination
x < 0
x <= 1
x < 10
- I only
- II only
- I and II only
- I and III only
- I, II and III
- inputVal % k == 0
- k % inputVal == 0
- inputVal % k != 0
- inputVal / k == 0
- k / inputVal > 0
- I only
- II only
- I and II only
- I and III only
- I, II and III
- 2
- n - 1
- n - 2
- (n - 1) * (n - 1)
- n * n
Q1: Given the following code segment:
int x = 1;
while ( /* condition */ ) {
if (x % 2 == 0) {
System.out.print(x + " ");
}
x = x + 2;
}
Consider the following conditions to replace /* condition */
in the code segment:
For which of the conditions will nothing be printed?
Q2: Given the following code segment which is intended to print the number of integers that evenly divide the integer inputVal. (You may assume that inputVal > 0.)
int count = 0;
int inputVal = /* user entered value */
for (int k = 1; k <= inputVal; k++) {
if ( /* condition */ ) {
count++;
}
} // end for
System.out.println(count);
Which of the following can be used to replace /* condition */ so that numDivisors will work as intended?
Q3: Which of the following code segments will produce the output:
1 4 7 10 13 16 19
int k = 1;
while (k < 20) {
if (k % 3 == 1)
System.out.print(k + " ");
k = k + 3;
}
for (int k = 1; k < 20; k++) {
if (k % 3 == 1)
System.out.print(k + " ");
}
for (int k = 1; k < 20; k = k + 3) {
System.out.print(k + " ");
}
Q4: What is the maximum number of times “Hello” can be printed?
int k = // a random number such that 1 <= k <= n ;
for (int p = 2; p <= k; p++) {
for (int r = 1; r < k; r++)
System.out.println("Hello");
}