Computers can run instructions on their own, leaving us to work on more interesting and creative problems. But computers can’t make decisions on their own. Programmers can give them multiple sets of instructions and describe the right conditions in which to use each set.
They can describe a structure like the quoted program below: “if X, then do instruction set 1. Otherwise do instruction set 2.” This structure is called a conditional control structure because the computer’s instructions depend on some condition(s).
Conditional control structures, or just conditionals, allow programs to do different things in different scenarios. As you can see, they follow a logic similar to how humans think, making it easy to write clear code while still handling complex processes.
The control flow is built using conditions. Once it is determined whether a condition is TRUE or FALSE the program knows what actions to take and will then continue on to the next condition to repeat the process.
A concrete analogy to control flow is traffic management 🚦. The traffic lights on the road regulate the traffic. They determine the order in which cars are allowed to drive at every moment.
When the driver reaches a traffic light he faces 3 possible conditions:
- Condition 1: light = red?
- Condition 2: light = orange?
- Condition 3: light = green?
Each condition will make the driver execute an action:
- Condition 1 = true => stop the car
- Condition 2 = true => stop the car if still possible, otherwise continue driving
- Condition 3 = true => continue driving
Here the traffic lights represent the ensemble of conditions that make up the control flow.
Updated over 2 years ago