## Section6.3Assessment: Writing Loops

### Subsection6.3.1Subgoals for Writing a Loop

1. Determine purpose of loop

1. Pick a loop structure (while, for, do_while)

2. Define and initialize variables

3. Determine termination condition

1. Invert termination condition to continuation condition

4. Write the loop body

1. Update Loop Control Variable to reach termination

### Exercises6.3.2Exercises

#### 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:

1. x < 0

2. x <= 1

3. 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.)

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?

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

• 2

• n - 1

• n - 2

• (n - 1) * (n - 1)

• n * n