Skip to main content

Section 6.1 Worked Example: While Loops - Counter

Subgoals for Evaluating a Loop.

  1. Identify loop parts
    1. Determine start condition
    2. Determine update condition
    3. Determine termination condition
    4. Determine body that is repeated
  2. Trace the loop
    1. For every iteration of loop, write down values

Subsection 6.1.1

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);

Subsection 6.1.2 SG1: Diagram which statements go together.

Figure 6.1.1.

Subsection 6.1.3 SG2: Define and initialize variables

Start:
counter = 0;
total = 0;
End:
counter >= 50
Figure 6.1.2.

Subsection 6.1.4 SG3: Trace the loop

Figure 6.1.3.
System.out.println(total);
Figure 6.1.4.
  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
Figure 6.1.5.
Figure 6.1.6.
Output is 225

Practice Pages.

You have attempted of activities on this page.