Module 1 · First Steps · Lesson 3 of 37
Decisions, Loops and Tracing Program State
Prerequisites and outcomes
You can declare integers and Booleans, calculate expressions, and explain the difference between parsing and range validation. This lesson introduces control flow: the rules that determine which statement runs next.
By the end, you will be able to:
- Select one outcome with an if/else chain and test its boundary values.
- Trace a loop's changing variables without guessing its final result.
- Use break and continue deliberately while preserving termination.
StudyDeck needs to accept some proposed study sessions, skip others, and calculate a total. A loop repeats work; a decision chooses whether a particular piece of work should run. Neither construct supplies its own business rules. We must state those rules explicitly. The analogy section pictures the process as a checklist with a visible running total.
Make a decision from a Boolean
An if statement executes its body when its condition is true. An else body handles the alternative. Braces group several statements into a block.
int minutes = 30;
if (minutes >= 1 && minutes <= 240)
{
Console.WriteLine("Allowed duration");
}
else
{
Console.WriteLine("Choose 1 through 240");
}The output is Allowed duration. Changing minutes to 0 selects the other message. A single if/else chooses one of these two bodies, not both. An else if adds a condition checked only when the earlier condition was false. Order matters when conditions overlap. Microsoft: selection statements
For example, checking minutes > 0 before minutes > 120 in an else-if chain means 150 enters the first branch. If the intended labels are “long” and “short,” test the narrower long condition first or organize the ranges so their meaning is clear. Several independent if statements are different: more than one may run.
Example 1: process three proposals
For this small experiment, proposals are 10, 20, and 30 minutes. All satisfy StudyDeck's general 1–240 rule, but today's demonstration schedule accepts only proposals up to 20 minutes. This extra scheduling choice is not a change to the application's global duration rule.
int total = 0;
int accepted = 0;
for (int session = 1; session <= 3; session++)
{
int proposed = session * 10;
if (proposed > 20)
{
Console.WriteLine($"Skipped session {session}");
continue;
}
total += proposed;
accepted++;
Console.WriteLine($"Accepted {proposed}; total {total}");
}
if (total >= 30)
{
Console.WriteLine("Goal reached");
}
else
{
Console.WriteLine("Keep planning");
}
Console.WriteLine($"Accepted sessions: {accepted}");Output:
Accepted 10; total 10 Accepted 20; total 30 Skipped session 3 Goal reached Accepted sessions: 2
A for loop has an initializer, a condition, and an iterator expression. Here the initializer creates session with value 1. The condition is checked before each body execution. The iterator session++ increases it by one after an ordinary iteration. The loop stops when the condition becomes false. Microsoft: iteration statements
The variables total and accepted exist outside the body so later iterations can use their accumulated values. proposed is created inside the block for each iteration. Scope means the region where a variable's name can be used; proposed cannot be referenced after its block.
Trace the state before trusting it
State is the set of relevant current values. Write a small trace table:
| session at body entry | proposed | action | total afterward | accepted afterward |
|---|---|---|---|---|
| 1 | 10 | accept | 10 | 1 |
| 2 | 20 | accept | 30 | 2 |
| 3 | 30 | skip | 30 | 2 |
When session becomes 4, session <= 3 is false, so there is no fourth body execution. The final goal comparison uses total 30. Because the comparison is >=, equality counts as success.
continue skips the remaining statements of the current loop iteration. In this for loop, control still proceeds to the iterator before the next condition check. It does not reset total or restart the entire program. break exits the nearest enclosing loop instead. These are distinct operations. Microsoft: jump statements
An off-by-one error is a boundary mistake that performs one too many or one too few iterations. Replacing <= 3 with < 3 would process only sessions 1 and 2. Whether that is wrong depends on the stated requirement, not on which symbol looks more familiar.
Example 2: repeat until a quantity is exhausted
A while loop checks a condition before every iteration. It is useful when the stopping rule is expressed in changing state rather than a known number of passes.
This complete independent program splits 25 minutes into blocks of at most 10:
int remaining = 25;
while (remaining > 0)
{
int block = 10;
if (remaining < block)
{
block = remaining;
}
Console.WriteLine(block);
remaining -= block;
}
Console.WriteLine("Done");Output:
10 10 5 Done
The loop has a progress argument: while remaining is positive, block is positive and no larger than remaining. Subtracting block reduces remaining without passing below zero. Eventually it reaches zero. If remaining starts at zero, the body runs zero times and only Done is printed.
This reasoning is more useful than saying “while loops eventually stop.” They stop only when their condition becomes false or another control transfer exits them.
A misconception with a counterexample
“Continue always makes a loop move forward” is false. In this deliberately broken fragment, the change that would make progress is skipped:
int attempt = 0;
while (attempt < 3)
{
continue;
// An increment placed here would never execute.
}Do not run this fragment as written: its condition never changes and it does not terminate normally. The for-loop example still advanced because its iterator is a separate part of that loop's control structure.
Another common mistake is resetting total = 0; inside the loop. That discards the earlier accumulated state on each pass. Put initialization at the boundary that matches the intended lifetime.
Exercises with solutions
1. Change the goal. In Example 1, replace the target 30 with 31. Predict every changed output line without rerunning.
Solution: Only Goal reached becomes Keep planning. Proposal handling and total accumulation occur before that comparison, so the accepted and skipped lines remain the same.
2. Repair a nonterminating countdown. A loop begins with remaining equal to 3, prints it while remaining is positive, but never changes it. Repair it to print 3, 2, 1.
Solution: Add remaining--; after the print inside the body. The sequence of values at the condition is 3, 2, 1, then 0. Do not decrement twice or place the only decrement on a path skipped by continue.
Interview questions with reasoning
When can a while body execute zero times? When its initial condition is false. This matters for empty or already-completed work, which should not require a fake first iteration.
What is the difference between break and continue? Break leaves the nearest enclosing loop or switch statement. Continue skips the rest of the current iteration and follows that loop's next-iteration rules. A for iterator still runs after continue.
How would you investigate a wrong total? Trace initialization, each accepted addition, skipped paths, and the final comparison. Check whether initialization accidentally occurs inside the repeated work and whether inclusive bounds match the requirement.
Analogy
A study-room checklist with a running total
Picture a coordinator reviewing three proposed study sessions. Each proposal arrives at a numbered position on a checklist. The coordinator checks its duration, either accepts it and updates the running total or marks it skipped, then moves to the next position.
An if/else decision is the choice between the accept and reject instructions. A loop is the repeated checklist procedure. The running total belongs at the top of the page; erasing it before every proposal would lose the earlier accepted work. A trace table is simply a written record of the coordinator's state after each decision.
Continue resembles skipping the remaining actions for the current proposal. Break resembles closing the checklist altogether. Those actions have different consequences for later proposals.
The analogy breaks if you assume the coordinator will use common sense to repair missing instructions. A program will not invent a missing counter update. In a while loop, repeatedly skipping the update can leave the condition unchanged forever. The computer's progress must follow from the actual assignments and control flow, not from our expectation that a review ought to finish.
Quick reference
Decisions and loop tracing
if (condition)runs its block when a Boolean condition is true.- An
else ifchain selects the first matching branch; independent if statements may both run. for (int i = 1; i <= 3; i++)visits 1, 2, and 3.while (remaining > 0)may execute zero times.continueskips the rest of the current iteration; a for iterator still runs.breakexits the nearest enclosing loop or switch statement.- Initialize an accumulated total before the loop.
- A variable declared inside a block is not available outside that scope.
Trace the condition, changed values, and output at every pass. Test the exact endpoints. Explain why a value moves toward termination; a loop does not stop merely because you intended it to finish.