5.8. Assessment: Nested Loops¶
Subgoals for Evaluating a Loop
Diagram which statements go together.
Define and initialize variables
Determine the start condition.
Determine the update condition.
Determine the termination condition.
Determine body that is repeated.
Trace the loop.
For every iteration of the loop, write down the values.
- 4
- 8
- 10
- 16
- 20
- 0
- 1
- 2
- n - 1
- n - 2
- 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
- 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
- 20
- 45
- 55
- 100
- 385
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);
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");
}
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();
}

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 + " ");
}
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);
You have attempted of activities on this page