Section 7.1 Worked Example: While Loops - Counter
Subgoals for Evaluating a Loop.
Subsection 7.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 7.1.2 SG1: Diagram which statements go together.

Subsection 7.1.3 SG2: Define and initialize variables
Start:
counter = 0;
total = 0;
End:
counter >= 50

Subsection 7.1.4 SG3: Trace the loop

System.out.println(total);

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


Practice Pages.
You have attempted 1 of 2 activities on this page.