# 5.2. Worked Example: For Loops - CounterΒΆ

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.

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

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

```
total = 0;
for (int x = 5; x < 50; x++)
{
if (x % 5 == 0)
total += x;
}
System.out.println(total);
```

SG1: Diagram which statements go together.

SG2: Define and initialize variables

**Start:**

```
x = 0
total = 0
```

**End:**

```
x >= 50
```

SG3: Trace the loop

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

Output is 225

Practice Pages

You have attempted of activities on this page