5.1. Worked Example: While Loops - CounterΒΆ

Subgoals 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.

You can watch this video or read through the content below it.

Problem: Given the following code, what is the output?

```int counter = 0;
int total = 0;

while (counter < 50)
{
if (counter % 5 == 0)
total += counter;
counter++;
}

System.out.println(total);
```

SG1: Diagram which statements go together.

SG2: Define and initialize variables

Start:

```counter = 0;
total = 0;
```

End:

```counter >= 50
```

SG3: Trace the loop

System.out.println(total);

1. For every iteration of loop, write down values

Counter increments by 1 But only when it is evenly divisible by 5 is the value added to total

Output is 225

Practice Pages