Concepts / Loop Structures: For and While Loops

Loop Structures: For and While Loops

Iteration is the repeated execution of statements in a loop or recursive function, and understanding loop terminology is essential for writing correct loops.

  • Programming

Why State Matters

Iteration means executing statements repeatedly in a loop or recursive function. Repetition becomes understandable when you track the state of the variables that control the loop. Before a loop begins, variables need starting values. During each iteration, those variables may be increased, decreased, or combined with new values. The loop can continue correctly only when these changes match the condition that controls repetition.

Tracing Variable State

A counter and an accumulator

Trace a loop with a counter that begins at 0 and increases by 1 on each iteration, together with an accumulator that begins at 0 and adds the values 4, 7, and 2 in successive iterations.

Initialization: The counter starts at 0, and the accumulator starts at 0. Initialization assigns starting values before the loop begins.

First iteration: The accumulator adds 4 and becomes 4. The counter increases by 1 and becomes 1.

Second iteration: The accumulator adds 7 to its running total and becomes 11. The counter increases by 1 and becomes 2.

Third iteration: The accumulator adds 2 and becomes 13. The counter increases by 1 and becomes 3.

After three iterations, the counter is 3 and the accumulator is 13. The counter records how many iterations occurred, while the accumulator records the running total of the values added.

Point in the loopCounterAccumulatorChange made
Before iteration 100Starting values
After iteration 114Counter increases by 1; accumulator adds 4
After iteration 2211Counter increases by 1; accumulator adds 7
After iteration 3313Counter increases by 1; accumulator adds 2

A state trace separates the variable that counts iterations from the variable that builds a running total.

add 4; incrementadd 7; incrementadd 2; incrementStartcounter 0; total 0Iteration 1counter 1; total 4Iteration 2counter 2; total 11Iteration 3counter 3; total 13
How do the loop variables and running total change from initialization through each iteration?

Control Variables

Initialization assigns a starting value to a variable before the loop begins. Counters commonly start at 0, and many accumulators also start at 0. The choice of starting value matters because every later state depends on it.

A counter tracks how many times an event occurs. It changes by a fixed amount on each iteration, commonly by 1. An accumulator has a different purpose: it builds a running total by adding values that may vary from one iteration to the next. Both variables may begin at 0, but their roles are different.

An increment increases a variable by a fixed amount, usually 1. A decrement decreases a variable by a fixed amount. In a loop, these operations update the state that will be used during a later condition check or iteration.

TermRoleTypical changeQuestion it answers
InitializationSets a starting value before the loopAssigns the initial stateWhere does the variable begin?
CounterTracks how many times an event occursIncreases by 1 or another fixed amountHow many iterations or events have occurred?
AccumulatorBuilds a running totalAdds varying valuesWhat total has been built so far?
IncrementRaises a variableAdds a fixed amountHow does the variable move upward?
DecrementLowers a variableSubtracts a fixed amountHow does the variable move downward?
tracksbuildsCounterfixed increaseEvent countnumber of occurrencesAccumulatorvarying additionsRunning totalcombined values
What is the difference between a variable that counts events and one that combines values?

For and While Control Flow

Both for and while loops repeat statements, so both require a clear view of the loop's state. A for-style loop is commonly traced through initialization, condition checking, the loop body, and an update before the next check. A while-style loop is commonly traced by checking the condition, executing the body when the condition permits it, and ensuring that the body or its control process changes the relevant state. In either structure, initialization comes before repetition, and updates determine what the next iteration will see.

setup completecontinuestopbody completenext checkInitializationstarting stateConditioncontinue?Loop bodyrepeated statementsUpdateincrement or decrementStopcondition no longer permitsrepetition
How does control move through setup, condition checking, the body, and updating in a loop?

Avoiding Endless Repetition

An infinite loop occurs when repetition does not reach a stopping condition. A common cause is a control variable that is never updated. Another cause is an update that moves the variable in the wrong direction or by an amount that prevents the condition from becoming false. To avoid endless repetition, identify the variable involved in the condition and trace its value after every iteration.

effective updateeventually reaches stopmissing or ineffective updatecondition stays permittedControl variableinitial valueUpdated valuemoves toward stopping stateStopcondition no longer permitsrepetitionSame valueno effective updateRepeatcondition remains permitted
What happens to the loop condition and control variable on each pass, and why does the loop eventually stop or continue forever?
  • Using a control variable without initializing it

    The loop has no clearly defined initial state, making its behavior unreliable and difficult to trace.

    Fix: Assign the starting value before the loop begins.

  • Forgetting to update the control variable

    The condition may remain true indefinitely, producing an infinite loop.

    Fix: Add an effective increment or decrement that moves the control variable toward the stopping condition.

  • Confusing a counter with an accumulator

    The variable no longer represents the number of events or iterations.

    Fix: Use a fixed update for a counter and varying additions for an accumulator.

  • Updating in the wrong direction

    The variable can move away from the state that would end repetition.

    Fix: Trace the variable after each iteration and choose an increment or decrement that progresses toward the stopping condition.

For every loop, write down the control variable, its initial value, its update, and the condition that determines continuation. If you cannot explain how the update changes the next condition check, the loop is not yet easy to verify.

Practice the Trace

EASY

Create a state trace for a loop whose counter starts at 0 and increases by 1 on each iteration. Track the counter after four iterations. Then create a second trace for an accumulator that starts at 0 and adds 3, 5, 1, and 6 during those iterations. Identify which variable is the counter, which is the accumulator, and what each variable represents after the fourth iteration.

Hints
  • Write the initialization row before the first iteration.
  • Increase the counter by the same fixed amount each time.
  • Add the next input value to the accumulator at each iteration.
  • The counter should describe how many iterations occurred; the accumulator should describe the running total.
MEDIUM

A loop condition depends on a variable that starts at 5. The variable is never changed in the loop body. Explain why this may create an infinite loop, and describe the kind of update that would be needed to make progress toward a stopping condition.

Hints
  • Compare the variable's value before and after one iteration.
  • Ask whether the condition can become false if the value never changes.
  • An increment or decrement should move the variable toward the state required for stopping.

Key Takeaways

  1. Iteration is the repeated execution of statements in a loop or recursive function.
  2. Initialization assigns starting values before repetition begins.
  3. A counter tracks occurrences through fixed updates, while an accumulator builds a running total from varying values.
  4. Incrementing increases a variable and decrementing decreases it; these updates affect the next loop condition check.
  5. An infinite loop can result when the control variable is uninitialized, unchanged, or updated in a direction that does not lead toward stopping.

Key Takeaways

  • Trace a loop from initialization through condition checking, the repeated body, and variable updates.
  • Use counters to record how many events occur and accumulators to build running totals.
  • Use increments and decrements deliberately because they determine the next state of the loop.
  • Prevent infinite loops by ensuring that the control variable is initialized and updated toward a stopping condition.