Advanced Usage
Nested Loops
Nested `for` loops involve placing one loop inside another. This is commonly used in multidimensional array operations or complex algorithms:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
// Nested loop body
}
}
Infinite Loops
An infinite loop runs indefinitely. It's useful in scenarios where the program needs to run continuously until manually stopped:
for (;;) {
// Infinite loop body
}
Enhanced Condition Checking
The condition in a `for` loop is a pivotal component, determining the continuation or termination of the loop. It’s evaluated before each iteration and can involve complex logical expressions. For instance:
for (int i = 0; i < n && array[i] != target; i++) {
// Loop body
}
In this example, the loop continues as long as `i` is less than `n` and the `i`-th element of `array` is not equal to `target`. This demonstrates how multiple conditions can be combined using logical operators (`&&`, `||`).
Stepping Variations
The increment/decrement step is not limited to simple increments or decrements by 1. It can be any valid C expression, offering a range of possibilities:
Variable Step Size
The step can vary based on calculations or conditions within the loop.
for (int i = 0; i < n; i += stepSize) {
// Loop body
}
Decrementing Loop
It’s common to decrement the loop variable, especially when counting down or reversing operations.
for (int i = n - 1; i >= 0; i--) {
// Loop body
}
Non-Integer Steps
You can use non-integer types for the loop variable, though this is less common and should be handled carefully to avoid infinite loops.
for (double d = 0.0; d < 1.0; d += 0.1) {
// Loop body
}
Loop Unrolling
Loop unrolling is an optimization technique where multiple iterations of the loop are executed within a single iteration to reduce the overhead of loop control. For instance:
for (int i = 0; i < n; i += 4) {
process(array[i]);
process(array[i + 1]);
process(array[i + 2]);
process(array[i + 3]);
}
Conditional Loop Execution
The `for` loop can execute different code paths within its body based on conditions, making it versatile for various scenarios:
for (int i = 0; i < n; i++) {
if (condition1) {
// Code block 1
} else if (condition2) {
// Code block 2
}
}