# 5.6. Assessment: While and For 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.

- 0 2 1 0 2
- 0 2 0 2 0 2
- 0 2 1 0 2 1 0
- 0 2 0 2 0 2 0
- 0 1 2 1 2 1 2
- First: 15; Last: 27
- First: 15; Last: 28
- First: 16; Last: 27
- First: 16; Last: 28
- First: 16; Last: 29
- 0
- 6
- 12
- 24
- 30
- Prints the value in num
- Prints the sum of all the integers between 1 and num, inclusive
- Prints the sum of all even integers between 1 and num, inclusive
- Prints the sum of all odd integers between 1 and num, inclusive
- Nothing is printed, it is an infinite loop
- 5 20 5
- 5 20 10
- 5 25 5
- 5 25 10
- 30 25 10

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

```
int k = 0;
while (k < 10) {
System.out.print((k % 3) + " ");
if ((k % 3) == 0)
k = k + 2;
else
k++;
}
```

Q2: What are the first and last numbers printed by the following code segment?

```
int number = 15;
while (number < 28) {
System.out.println(number);
number++;
}
```

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

```
int alpha = 24;
int beta = 30;
while (beta != 0) {
int rho = alpha % beta;
alpha = beta;
beta = rho;
}
System.out.println(alpha);
```

Q4: Considering the following code, which best describes what the code does?

```
int var = 0;
int num = 50;
for (int x = 1; x <= 50; x += 2) {
var = var + x;
}
System.out.println(var);
```

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

```
int typeA = 0;
int typeB = 0;
int typeC = 0;
for (int k = 1; k <= 50; k++) {
if (k % 2 == 0 && k % 5 == 0)
typeA++;
if (k % 2 == 0)
typeB++;
if (k % 5 == 0)
typeC++;
}
System.out.printf("%d %d %d", typeA, typeB, typeC);
```

You have attempted of activities on this page