Invert termination condition to continuation condition
Write loop body
Update loop control variable to reach termination
ExercisesExercises
1.
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:
x < 0
x <= 1
x < 10
For which of the conditions will nothing be printed?
I only
II only
I and II only
I and III only
I, II and III
2.
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. Which of the following can be used to replace /* condition */ so that numDivisors will work as intended?
int count = 0;
int inputVal = /* user entered value */
for (int k = 1; k <= inputVal; k++) {
if ( /* condition */ ) {
count++;
}
} // end for
System.out.println(count);
inputVal % k == 0
k % inputVal == 0
inputVal % k != 0
inputVal / k == 0
k / inputVal > 0
3.
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 + " ");
}
I only
II only
I and II only
I and III only
I, II and III
4.
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");
}