Skip to main content

Section 5.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 5.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 5.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 5.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.
counter increments by 1 But only when the counter is evenly divisible by 5 is the value added to total.
Answer.
Output is 225
You have attempted of activities on this page.