## Section5.14Assessment: Nested Loops

### Subsection5.14.1Subgoals for Evaluating a Loop

1. Diagram which statements go together.

2. Define and initialize variables

1. Determine the start condition.

2. Determine the update condition.

3. Determine the termination condition.

4. Determine body that is repeated.

3. Trace the loop.

1. For every iteration of the loop, write down the values.

### Exercises5.14.2Exercises

#### 1.

Q1: What is printed as a result of executing the following code segment?

int count = 0;
for (int x = 0; x < 4; x++) {
for (int y = x; y < 4; y++)
count++;
}
System.out.println(count);

• 4

• 8

• 10

• 16

• 20

#### 2.

Q2: What is the minimum 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");
}

• 0

• 1

• 2

• n - 1

• n - 2

#### 3.

Q3: What is printed as a result of executing the following code segment?

for (int r = 3; r > 0; r--) {
int c;
for (c = 1; c < r; c++)
System.out.print("-");
for (c = r; c <= 3; c++)
System.out.print("*");
System.out.println();
}

• See diagram for answer A

• See diagram for answer B

• See diagram for answer C

• See diagram for answer D

• See diagram for answer E

#### 4.

Q4: What is printed as a result of executing the following code segment?

for (int outer = 0; outer < 4; outer++) {
for (int inner = 0; inner <= outer; inner++)
System.out.print(outer + "  ");
}

• 0 1 2 3

• 0 0 1 0 1 2

• 0 1 2 2 3 3 3

• 0 1 1 2 2 2 3 3 3 3

• 0 0 1 0 1 2 0 1 2 3

#### 5.

Q5: What is printed as a result of executing the following code segment?

int s = 0;
for (int outer = 1; outer <= 10; outer++) {
for (int inner = outer; inner <= 10; inner++)
s++;
}
System.out.println(s);

• 20

• 45

• 55

• 100

• 385