1. What Are Control Structures?
Control structures are syntactic constructs in programming languages used to control the execution path and execution order of a program.
By default, a program executes statements one by one in the order in which the code appears in the source file. However, real business logic usually includes conditional checks, repeated operations, and control-flow jumps; sequential execution alone cannot express complex logic.
For example:
- When a user logs in, the program needs to determine whether the account and password are correct.
- When processing an order, it needs to perform different operations based on the order status.
- When iterating over a collection, it needs to repeatedly execute a certain piece of logic.
- When an exception occurs, it needs to end the current operation early.
All of these behaviors rely on control structures.
From the perspective of how a program executes, control structures are usually divided into three categories:
- Sequence structure: executes statements one after another in the order in which they are arranged.
- Selection structure: decides which path to execute based on a condition.
- Iteration structure: repeatedly executes a piece of code while a condition is met.
In addition, mechanisms such as function calls, exception handling, and jump statements also affect a program's control flow.
2. Sequence Structure
Sequence structure is the most basic control structure: the program executes statements in the order in which they appear in the code.
flowchart TB
A["Start"] --> B["Execute statement A"]
B --> C["Execute statement B"]
C --> D["Execute statement C"]
D --> E["End"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
For example:
a = 10
b = 20
result = a + b
print(result)
The program performs variable assignment, calculation, and output in sequence.
2.1 Characteristics of Sequence Structure
- The execution order is determined by the positions in which the statements are arranged.
- By default, the next statement is executed only after the current statement has finished executing.
- No additional conditional checks are required.
- It is the foundation of branch structures and loop structures.
Note that sequence structure describes the logical execution order of a program; it does not mean that all program statements must be strictly executed serially at the physical level.
Compilers and processors may optimize the actual execution process through instruction reordering, pipelining, out-of-order execution, and other methods, but within the observable behavior specified by the language, correct program semantics must still be guaranteed.
3. Selection Structure
A selection structure decides which branch path the program takes based on the result of a conditional expression.
Common forms include:
ifif...elseif...else if...elseswitch- Pattern matching
- Conditional expression
3.1 if Statement
if is the most basic conditional selection structure.
age = 20
if age >= 18:
print("成年人")
Execution process:
flowchart TD
A["Start"] --> B["Check age >= 18"]
B --> C{"Is the condition true?"}
C -->|"Yes"| D["Output adult"]
C -->|"No"| E["Skip the conditional statement"]
D --> F["Continue execution"]
E --> F
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
When the conditional expression is true, the corresponding code block is executed; when it is false, the code block is skipped.
Different languages have different requirements for conditional expressions:
| Language | Conditional expression requirement |
|---|---|
| C | Scalar expressions are allowed; zero is false and non-zero is true |
| C++ | The conditional expression must be convertible to bool |
| Java | Must be of type boolean |
| JavaScript | Any value can be used, evaluated according to Truthy / Falsy rules |
| Python | Any object can be used, evaluated according to Truth Value Testing |
| Go | Must be of type bool |
For example, in JavaScript:
if ("hello") {
console.log("条件成立");
}
The string "hello" is converted to a truthy value.
But in Java, a string cannot be used directly as the condition of an if:
String value = "hello";
// Compile error: condition must be boolean
if (value) {
System.out.println("条件成立");
}
This is a difference that is easy to overlook in cross-language development.
3.2 if...else Statement
When different logic needs to be executed depending on whether the condition is true or false, you can use if...else.
score = 75
if score >= 60:
print("及格")
else:
print("不及格")
Execution flow:
flowchart TD
A["Start"] --> B["Check score >= 60"]
B --> C{"Pass?"}
C -->|"Yes"| D["Output Pass"]
C -->|"No"| E["Output Fail"]
D --> F["Continue"]
E --> F
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style F fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
The two branches of if...else are mutually exclusive: a single condition evaluation selects only one branch to execute.
3.3 if...else if...else Statement
When multiple conditions need to be evaluated, you can use a multi-branch structure.
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
elif score >= 60:
print("及格")
else:
print("不及格")
Execution flow:
flowchart TD
A["Start"] --> B{"score >= 90"}
B -->|"Yes"| C["Excellent"]
B -->|"No"| D{"score >= 80"}
D -->|"Yes"| E["Good"]
D -->|"No"| F{"score >= 60"}
F -->|"Yes"| G["Pass"]
F -->|"No"| H["Fail"]
C --> I["Continue"]
E --> I
G --> I
H --> I
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style H fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
A multi-branch structure has an important characteristic: conditions are evaluated one by one in code order; once the first condition that holds is matched, the corresponding branch is executed and the remaining branches are skipped.
Therefore, the order in which the conditions are arranged affects the program's result.
For example:
score = 95
if score >= 60:
print("Pass")
elif score >= 90:
print("Excellent")
The output is:
Pass
Because score >= 60 already holds, the later conditions are not evaluated.
The correct approach is to put the more specific, stricter conditions first:
if score >= 90:
print("Excellent")
elif score >= 60:
print("Pass")
else:
print("Fail")
3.4 switch Statements
switch is a multi-branch selection structure that usually matches different branches based on the value of an expression.
For example, in Java:
int status = 2;
switch (status) {
case 1:
System.out.println("Pending");
break;
case 2:
System.out.println("Processing");
break;
case 3:
System.out.println("Completed");
break;
default:
System.out.println("Unknown status");
}
Execution characteristics of the traditional switch:
- It looks for the matching
casebased on the value of the expression. - Once matched, the corresponding branch is executed.
- In syntaxes that support fall-through behavior, if no terminating statement such as
breakis encountered, execution may continue into subsequent branches. defaulthandles the situation where nothing matches.
The key thing to understand here is break.
In the traditional switch of C, C++, and Java, break is usually used to exit the entire switch structure, not merely to end the current case.
If break is omitted, branch fall-through may occur.
int value = 1;
switch (value) {
case 1:
System.out.println("A");
case 2:
System.out.println("B");
default:
System.out.println("C");
}
Output:
A
B
C
This is because after case 1 is matched, the program continues executing downward and does not automatically jump out of the switch.
Modern languages have made various improvements to switch:
| Language | Main characteristics |
|---|---|
| C | Mainly supports integer types, enums, and other qualifying control expressions |
| C++ | Supports integer types, enum types, and other qualifying control expressions |
| Java | Supports integers, enums, strings, and other types; modern versions also provide an enhanced switch |
| JavaScript | Uses strict equality comparison to match case |
| Go | No explicit break is needed; by default it does not fall through to subsequent branches |
| Rust | match is a more fundamental pattern-matching construct, and branches must cover all possible cases |
For example, in Go:
status := 2
switch status {
case 1:
fmt.Println("待处理")
case 2:
fmt.Println("处理中")
case 3:
fmt.Println("已完成")
default:
fmt.Println("未知状态")
}
Go's switch exits by default after the matching branch finishes executing, so there is no need to explicitly add break as with a traditional Java switch.
3.5 Pattern Matching
Pattern matching is a more flexible selection mechanism than a traditional switch.
It can not only determine whether values are equal, but also match based on combinations of data structures, types, fields, and values.
For example, in Rust:
enum Status {
Pending,
Processing,
Completed,
}
let status = Status::Processing;
match status {
Status::Pending => println!("待处理"),
Status::Processing => println!("处理中"),
Status::Completed => println!("已完成"),
}
The core capabilities of pattern matching include:
- Value matching: matching specific constants or values.
- Type matching: selecting a branch based on the data type.
- Structure matching: matching data structures such as tuples, structs, and enums.
- Destructuring: extracting internal fields from the matched data structure.
- Guard conditions: adding extra checks on top of pattern matching.
The main difference between pattern matching and traditional conditional judgment is that it can perform condition selection and data structure destructuring at the same time, reducing complex nested judgments.
IV. Iteration
Loop structures are used to execute a section of code repeatedly.
When an operation needs to be performed multiple times, there is no need to write the same code over and over; instead, a loop structure controls the number of repetitions and the termination condition.
Common loop structures include:
whiledo...whileforforeach/for...in- Iterator
4.1 while Loop
A while loop evaluates the condition before each execution of the loop body.
As long as the condition holds, the loop body continues to execute; when the condition no longer holds, the loop exits.
count = 1
while count <= 5:
print(count)
count += 1
Execution process:
flowchart TD
A["Initialize count = 1"] --> B{"count <= 5"}
B -->|"Yes"| C["Execute loop body"]
C --> D["count += 1"]
D --> B
B -->|"No"| E["Exit loop"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Key characteristics of while:
- It evaluates the condition first, then executes the loop body.
- If the condition does not hold initially, the loop body is never executed even once.
- It is suitable for scenarios where the number of iterations is uncertain and mainly depends on condition control.
4.2 do...while Loop
The main difference between do...while and while is that it executes the loop body first and then evaluates the condition.
int count = 1;
do {
System.out.println(count);
count++;
} while (count <= 5);
Execution process:
flowchart TD
A["Start"] --> B["Execute loop body"]
B --> C["Update loop variable"]
C --> D{"Check loop condition"}
D -->|"Yes"| B
D -->|"No"| E["Exit loop"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Therefore, a do...while loop executes its body at least once.
Applicable scenarios:
- User input validation.
- Menu interaction.
- Logic where an operation must be performed once before deciding whether to continue.
Note that languages such as Python and Go do not have native do...while syntax, but the same logic can be implemented using other loop structures.
4.3 for Loop
The for loop is typically used when the number of iterations is known, or when there is a clear iteration rule.
Taking C as an example:
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
The traditional for structure consists of three parts:
for (initialization expression; condition expression; update expression) {
// loop body
}
The roles of the three parts:
| Part | Role | When it executes |
|---|---|---|
| Initialization expression | Initializes the loop variable | Executed once at the start of the entire loop |
| Condition expression | Determines whether to continue looping | Before each execution of the loop body |
| Update expression | Updates the loop variable | After each execution of the loop body completes |
Execution order:
flowchart TD
A["Initialization expression"] --> B{"Evaluate condition expression"}
B -->|"True"| C["Execute loop body"]
C --> D["Execute update expression"]
D --> B
B -->|"False"| E["Exit loop"]
style A fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style D fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style E fill:#E8EDF2,stroke:#B8C3CE,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that the three expressions of a for loop do not all have to be present.
For example:
for (;;) {
// infinite loop
}
Since there is no termination condition, the loop will continue executing unless it is exited through break, return, or another control mechanism.
4.4 foreach and for...in
Iterating over collections is a very common operation in programming.
Many languages provide dedicated syntax for collection traversal, for example:
Python:
names = ["Alice", "Bob", "Charlie"]
for name in names:
print(name)
Java:
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}
JavaScript:
const names = ["Alice", "Bob", "Charlie"];
for (const name of names) {
console.log(name);
}
These syntaxes can avoid manually managing indexes and make code more concise.
However, note that traversal semantics are not exactly the same across languages.
| Language | Traversal syntax | Main behavior |
|---|---|---|
| Python | for...in |
Iterates over elements in an iterable object |
| Java | Enhanced for |
Iterates over arrays or objects implementing Iterable |
| JavaScript | for...of |
Iterates over the values of an iterable object |
| JavaScript | for...in |
Iterates over the enumerable property keys of an object |
| Go | for...range |
Iterates over arrays, slices, strings, maps, channels, etc. |
| Rust | for...in |
Iterates over elements through an iterator |
Pay special attention to JavaScript:
const names = ["Alice", "Bob", "Charlie"];
for (const index in names) {
console.log(index);
}
for (const name of names) {
console.log(name);
}
for...in outputs property keys, which in arrays usually appear as index strings; for...of outputs element values.
The two cannot be used interchangeably.
4.5 Iterators (Iterator)
An iterator is an abstraction mechanism for accessing the elements of a collection one by one.
It separates how a collection stores data from how its elements are traversed, allowing different data structures to provide a unified traversal interface.
Iterators usually include the following core operations:
- Get the next element.
- Determine whether there are more elements.
- Return the current element.
- Maintain state during traversal.
Iterator interfaces differ across languages:
| Language | Related mechanisms |
|---|---|
| Java | Iterator, Iterable |
| Python | Iterator, Iterable, __next__() |
| JavaScript | Iterator, Symbol.iterator |
| C++ | Iterator, Range-based for |
| Rust | Iterator Trait |
| Go | Often implemented through range or a custom traversal interface |
For example, in Python:
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator))
print(next(iterator))
print(next(iterator))
Output:
10
20
30
iter() obtains an iterator, and next() requests the next element.
When an iterator has no more elements, Python raises StopIteration, while for...in automatically handles this end signal.
The value of iterators lies not only in traversing collections; they can also support:
- Lazy evaluation (Lazy Evaluation).
- Streaming data processing.
- Incremental reading of large datasets.
- Generators and pipeline-style processing.
- Reducing the creation of intermediate collections.
V. Loop Control Statements
Loop structures usually also need to work with control statements to alter the normal execution flow of the loop.
Common loop control statements include:
breakcontinuereturngoto(supported by some languages)
5.1 break: Terminate the Loop
break is used to immediately end the current loop structure and jump to the code after the loop to continue execution.
for i in range(10):
if i == 5:
break
print(i)
Output:
0
1
2
3
4
When i == 5, break is executed and the entire loop ends.
Note that break usually only terminates the current innermost loop, rather than automatically terminating all nested loops.
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)
After the inner loop ends, the outer loop will still continue to execute.
5.2 continue: Skip the current iteration
continue is used to end the current loop iteration and proceed to the next loop condition check or iteration.
for i in range(5):
if i == 2:
continue
print(i)
Output:
0
1
3
4
When i == 2, the remaining code in this iteration is skipped, but the loop itself does not end.
The difference between break and continue:
| Statement | Effect | Subsequent behavior |
|---|---|---|
break |
Terminate the current loop | Exit the loop |
continue |
Skip the current iteration | Proceed to the next iteration |
5.3 return: End function execution
return is used to return from the current function to the caller.
It can not only terminate the loop but also end all subsequent execution inside the function.
def find_number(numbers, target):
for number in numbers:
if number == target:
return True
return False
result = find_number([1, 3, 5, 7], 5)
print(result)