Concepts / Counting with Loops

Counting with Loops

Data scanning loops follow a three-step construction: initialize variables before the loop, perform computation on each item inside the loop body, and examine results after the loop completes.

  • Programming
Interactive lab

Try it: Loop Tracer

How a Python for loop visits each item in turn, and how an accumulator variable (a total, a count, a best-so-far or a result list) changes on every iteration.

How it works

  1. Initialise the accumulator before the loop.
  2. Each iteration, the loop variable takes the next value from the list.
  3. An if inside the loop decides whether to update the accumulator.
  4. After the last item the loop ends and the accumulator holds the answer.

Default run (13 steps): values = [4, 9, 2, 7, 5]. Run the loop one statement at a time. … The loop has used every value. print(total) shows 27.

Simplified: A model of five fixed loop programs (sum, count, maximum, minimum, filter) run on your list — it steps the program exactly as Python would, but it does not run Python.

Educational simulation

Loading the simulation…

Why Scanning Needs a Pattern

Many programming tasks require examining every item in a collection, such as a list, a file, or a sequence of user inputs. The task might be finding the largest number, locating the smallest value, summing values, or counting items that meet a condition. A loop avoids writing separate instructions for each item by repeating the same examination process.

A data-scanning loop has a dependable three-step shape: initialize variables before the loop, perform computation on each item inside the loop body, and examine the result after the loop completes. The particular variable and computation may change from one task to another, but this overall structure remains the same.

Initializevariablesstarting valuesProcess each itemcompute or compareExamine resultafter the loopbefore loopafter all items
What happens before scanning begins, during each iteration, and after every item has been processed?

Tracing a Maximum Search

Consider a list containing the values 3, 7, 2, 9, and 5. The goal is to find the largest value. The result variable begins at 3, before the loop starts. The loop then examines each item and compares it with the current maximum.

Worked example

Finding the Largest Value

Scan the values 3, 7, 2, 9, and 5 and track the largest value found so far.

  1. 1
    Initialize

    Set max_value to 3 before the loop begins. This gives the result variable a starting value.

  2. 2
    Process 7

    The current item, 7, is larger than max_value, so max_value changes from 3 to 7.

  3. 3
    Process 2

    The current item, 2, is not larger than max_value, so max_value remains 7.

  4. 4
    Process 9

    The current item, 9, is larger than max_value, so max_value changes from 7 to 9.

  5. 5
    Process 5

    The current item, 5, is not larger than max_value, so max_value remains 9.

  6. 6
    Examine

    After the loop has visited every item, examine max_value to obtain the largest value found.

Result

The final max_value is 9.

3current item; max 37current item; max 72current item; max 79current item; max 95current item; max 9next itemnext itemnext itemnext item
How do the current item and accumulated maximum change as the loop scans the data?

Conditional State Updates

The important state in a scanning loop is the information accumulated so far. In the maximum search, max_value changes only when the current item is larger than the value already stored. If the current item is smaller, the loop still examines it, but the accumulated result does not change.

This decision point is what makes the pattern useful. The loop does not blindly replace the result variable. It compares the current item with the accumulated result, then either stores a new result or keeps the existing one. The same kind of conditional update can support maximum searches, minimum searches, sums, counts, and searches for specific values.

Roles of the Loop Variables

A scanning loop can be understood by asking three questions about its variables. What value must exist before scanning begins? What information is examined or computed for each current item? What result is read after the final iteration? These questions identify the initialization, per-item computation, and final examination stages.

Starting valueinitialize before loopCurrent itemone item per iterationComparison or testinside loop bodyAccumulated resultupdated when neededFinal valueexamine after loopinitial stateitem inputcondition metnext stateafter all items
Where is each part of the loop's state introduced, changed, and read?
StageQuestion to askRole in the loop
Before the loopWhat starting value is needed?Initialize the result-tracking variables.
Inside the loopWhat should happen for the current item?Compute, compare, or test the item and update state when appropriate.
After the loopWhat does the final state tell us?Examine the completed result.

Use these questions to plan a data-scanning loop.

Adapting the Pattern

The three stages stay constant while the details change. For a maximum search, the result tracks the largest value and changes when a larger item appears. For a minimum search, the comparison is adapted to the smallest value. For a sum or count, the result is updated according to the required computation. For a search for a specific value, each item is tested against the target and the result records the outcome required by the task.

Worked example

Planning a Specific-Value Search

Design the stages of a loop that scans data to determine whether a specific value appears.

  1. 1
    Initialize

    Choose a result variable with a starting value that represents the state before any item has been tested.

  2. 2
    Process each item

    Compare the current item with the target value. If the required condition is met, update the result according to the search task.

  3. 3
    Continue scanning

    Visit the remaining items. The result changes only when the defined test requires a change.

  4. 4
    Examine

    After the loop completes, read the result variable to determine what the full scan established.

Result

The loop follows the same initialize, process, and examine structure even though its test differs from a maximum search.

MEDIUM

Plan a scanning loop that counts how many items in a collection meet a chosen condition. State what must be initialized before the loop, what happens for each current item, when the result changes, and what is examined after the loop.

Hints
  • Identify the result variable that will track the count.
  • Describe the test applied to each current item.
  • Remember that the result changes only when the condition is met.
  • The final count is examined after every item has been scanned.

Mistakes in Loop Design

  • Common mistake

    Initializing the result variable inside the loop instead of before it.

    What it looks like

    The accumulated result is given a starting value again each time an item is processed.

    Why it fails

    The loop needs a state that carries information from one iteration to the next. Reinitializing it prevents the previous work from being retained.

    Do this instead

    Initialize result-tracking variables before the loop begins.

  • Common mistake

    Assuming the result must change on every iteration.

    What it looks like

    Replacing the current maximum even when the current item is smaller.

    Why it fails

    Scanning updates are conditional. An item that does not satisfy the comparison or test should leave the accumulated state unchanged.

    Do this instead

    Define the comparison or test clearly and update state only when its condition is met.

  • Common mistake

    Examining the result before the loop has processed every item.

    What it looks like

    Treating an intermediate maximum as the final maximum.

    Why it fails

    A later item may still change the result.

    Do this instead

    Examine the completed result after the loop finishes.

  • Common mistake

    Changing the computation without reconsidering the initialization.

    What it looks like

    Using the same starting arrangement for a maximum search, a minimum search, a sum, and a count without checking whether each task needs a different initial state.

    Why it fails

    The general pattern is shared, but what you initialize, compute, and examine depends on the scanning task.

    Do this instead

    Design the starting value and update rule together for the specific task.

Summary

  1. 1
    A data-scanning loop follows three stages: initialize before the loop, compute or test each item inside the loop, and examine the result afterward.
  2. 2
    Result variables such as a maximum, minimum, sum, or count need a starting value before scanning begins.
  3. 3
    State changes are conditional, so some iterations update the result while others leave it unchanged.
  4. 4
    The same structure can be adapted for maximums, minimums, sums, counts, and searches for specific values.
  5. 5
    Reliable loop design comes from separating initialization, per-item processing, and final examination.

At a glance

  • Initialize the state before scanning starts.
  • Process every item inside the loop and update the state only when the required condition is met.
  • Examine the accumulated result after all iterations finish.
  • Adapt the initialization and update rule to the task: finding, summing, counting, or comparing values.

More concepts starting with C