Skip to main content

Section 6.1 While Counter

Subgoals for Evaluating a Loop.

  1. Determine Loop Components
    1. Start condition and values
    2. Iteration variable and/or update condition
    3. Termination/final condition
    4. Body that is repeated based on indentation
  2. Trace the loop, writing updated values for every iteration or until you identify the pattern

Subsection 6.1.1

Problem: Given the following code, what is the output?
counter = 0
total = 0
while counter < 50:
    if counter % 5 == 0:
        total += counter
    counter += 1
print(total)

Subsection 6.1.2 Determine loop components

Starting values:
counter = 0
total = 0
Termination condition:
while counter < 50:
Body that is repeated based on indentation:
if counter % 5 == 0:
    total += counter
counter += 1

Subsection 6.1.3 Trace the loop, writing updated values for every iteration or until you identify the pattern

For every iteration of loop, write down values.
Trace of the loop (counter is 0 to 10)
counter increments by 1 But only when the counter is evenly divisible by 5 is the value added to total.
Trace of the loop (counter is 10 to 35)
Trace of the loop (counter is 35 to 50)
Answer.
Output is 225
You have attempted of activities on this page.