Control Structures
Learning Objectives
- Define control structures and their role in program execution flow.
- Implement selection statements including
if,if-else,else-if, andswitch. - Explain the concept of short-circuit evaluation and its performance benefits.
- Understand and apply the ternary operator for simple conditional assignments.
- Implement iteration using
for,while, anddo-whileloops. - Identify and prevent infinite loops.
- Utilize jump statements like
break,continue, andreturnto alter loop execution.
A comprehensive guide to conditional statements (if-else, switch), short-circuit evaluation, and looping constructs (for, while, do-while).
Control Structures
Control Structures are blocks of code that dictate the flow of execution in a program. They allow programs to make decisions (branching) and repeat tasks (looping) based on logical conditions, moving away from simple sequential execution.
1. Conditional Statements (Selection)
These structures allow the program to execute different blocks of code based on whether a boolean condition evaluates to True or False.
Condition
A Condition is an expression that evaluates to a boolean value (True or False), dictating which branch of code a control structure will execute.
1.1 The if Statement
The simplest form of decision making. The code block inside runs only if the specified condition is true. If false, the program skips the block entirely and continues with the rest of the code.
1.2 The if-else and else-if Statements
Provides alternative blocks of code. The else block executes if the initial condition is false. An else-if (or elif) ladder allows checking multiple sequential conditions. Once a true condition is found, its block executes, and the rest of the ladder is skipped.
1.3 The Ternary Operator (?:)
The Ternary Operator is a shorthand for a simple if-else statement. It takes three operands: a condition, a result for True, and a result for False. Syntax: condition ? true_result : false_result.
1.4 Short-Circuit Evaluation
In languages whose logical AND (&&) and OR (||) operators short-circuit, the left operand is evaluated first and the right operand is skipped when the left value already determines the result. This conditional evaluation can avoid unnecessary work and can guard an operation that would be invalid for a particular input.
Short-Circuit Examples
AND (
A && B): IfAis false, the result is false andBis not evaluated. A guard such asdivisor != 0 && x / divisor > 5avoids evaluating the division when the divisor is zero in languages and numeric types where that division would raise an error. Division-by-zero behavior varies by language and type.OR (
A || B): IfAis true, the result is true andBis not evaluated. Otherwise the right operand is evaluated.
When AND and OR skip the right operand
The right side runs only when the left side cannot determine the result. In the divisor guard, the comparison is evaluated before the division expression.
1.5 The switch Statement (C++, Java, JS)
A switch compares one expression with a set of case alternatives. It can make selection clearer when the alternatives fit the language's matching rules. Case-expression rules and fall-through behavior vary by language.
Choosing a Switch
Prefer a switch when one expression is matched against alternatives that fit the language's case rules; use if-else when conditions involve ranges or unrelated tests. Do not assume a switch is always faster or has constant-time lookup: implementation and case layout affect how it is executed. In JavaScript, a matching case can fall through to later cases unless control leaves the switch, commonly with break.
If chains, switch cases, and ternary expressions
An if chain checks conditions in order; a switch matches one expression according to language-specific case rules; a ternary expression selects one of two result expressions. The snippets are schematic JavaScript-style examples.
2. Looping Statements (Iteration)
Loops repeat a body while their continuation rules allow another iteration. The construct controls where its condition is checked and how execution advances; iteration count may or may not be known in advance.
Infinite Loop
An Infinite Loop is a loop whose control flow continues indefinitely because no reachable condition or other exit stops further iterations. An infinite loop may be intentional; it does not necessarily crash the whole program.
Infinite Loops
Check how each loop can terminate and whether its state changes can reach that exit. A missing update can create an unintended infinite loop, which may keep a thread busy until the program or loop is stopped. Some service and event loops intentionally continue until a stop signal or other exit occurs.
2.1 The for Loop
A counter-controlled for loop commonly keeps initialization, a continuation test, and an update together. It is often used when the iteration pattern is clear, but the syntax does not guarantee that the number of iterations is known beforehand; collection-style for loops are also common.
Interact with the simulation below to step through a for-loop and see how the initialization, condition, and update steps dictate the execution flow.
For Loop Execution
Console Output:
2.2 Interactive Loop Visualizer
Watch how a for loop executes step-by-step. Pay attention to the initialization, condition check, body execution, and increment.
Loop Execution Visualizer
2.3 The while Loop
A while loop tests its condition before each pass through the body. If the condition is false when first tested, the body runs zero times. It is often useful when repetition depends on a condition rather than a predetermined count.
2.4 The do-while Loop
A do-while loop runs its body before testing the continuation condition. When control reaches the loop, its body begins at least once; a break, exception, or other control transfer can still leave it early. It is useful when the first interaction or attempt must happen before the test.
Pre-test while and post-test do-while loops
The key distinction is test position: while tests before the body; do-while tests after the body. With the same initially false condition, the first executes zero body passes and the second executes one.
2.5 Nested Loops
Loops can be nested to process rows and columns in a matrix or grid. If both an outer and inner loop each run times, the body executes times; different bounds, early exits, and input-dependent behavior change the overall complexity.
3. Loop Control Statements (Jump Statements)
These statements transfer control out of a normal path. Within loops, break can exit the innermost loop and continue can skip the remainder of the current iteration. return exits the current function, which also ends any loop running inside it.
Control Statements
Break: In a loop, exits the innermost enclosing loop and continues after it. In a
switch, it exits thatswitch; languages with fall-through may use it to prevent execution from continuing into the next case. Some languages also support labeled exits.Continue: Skips the rest of the current iteration and proceeds through the loop's next-iteration behavior. In JavaScript,
continuereaches aforloop's update expression before its next condition check; for awhileloop it returns to the condition.Return: While primarily used to exit a function and send a value back to the caller, if used inside a loop within a function, it will immediately terminate both the loop and the function.
Where break, continue, and return transfer control
The destination depends on the statement: break exits a loop or switch, continue advances the current loop, and return exits the function and resumes at its caller. The continue note follows JavaScript loop semantics.
- Selection constructs choose a path or result; use each construct according to its condition and case rules.
- In short-circuit AND and OR operators, the right operand is evaluated only when the left operand does not determine the result.
- A
forloop often groups initialization, testing, and update;whiletests before its body;do-whiletests after its body. - Nested-loop cost depends on how many times each loop runs, not only on the syntax used.
breakexits a loop or switch,continueadvances the current loop, andreturnexits the current function.- Check every intended and unintended loop exit; infinite loops can be deliberate and need not crash a program.