Concept: The Apple Factory
Imagine you are managing a quality control conveyor belt. Your logic is cleanly divided into two specific responsibilities:
The Loop (Duration)
"How long should I keep working?" You continue inspecting as long as the conveyor belt is not empty. When it's empty, you stop. We use a while loop because we don't know the exact count in advance.
The Condition (Selection)
"What do I do with this item?" For each apple, check its color. If it is Red, pack it in a box. Otherwise (Green), send it to the juicer.
Memory State (記憶體狀態)
Trace Table (追蹤表)
| Action | belt | apple | packed | juiced |
|---|
Think & Link
What would happen if we swapped the while condition and the if condition? For example, if we wrote `while apple == 'R'`? Draft your logic below.
Expert Analysis
If you use while apple == 'R', the loop terminates the very first time it encounters a green apple. It will ignore the rest of the array completely! The `while` loop determines the duration (iteration), not the filtering (selection).
Knowledge Check
In a `while` loop processing an array, if an item triggers the else branch, what happens immediately after the `else` block finishes executing?