Control Flow
By default, a program is executed from top to bottom, one line at a time.
This linear execution is simple, but it is not enough to handle real-world problems.
Control flow allows us to control how and when parts of a program are executed.
With control flow, a program can:
- repeat actions
- make decisions
- react differently based on conditions
Why Control Flow Matters
Without control flow:
- programs would always run in a straight line
- there would be no decisions
- there would be no repetition
Control flow is what makes programs dynamic and intelligent, instead of static scripts.
Types of Control Flow
In this section, control flow is divided into two main categories:
1. Loop
Loops are used to repeat a block of code multiple times.
They are useful when:
- an action needs to be performed repeatedly
- the number of repetitions is known or unknown
You can think of a loop like a wheel that keeps turning until a certain condition is met.
2. Conditional
Conditionals are used to control the flow of a program based on conditions.
They allow a program to:
- choose between different paths
- execute code only when a condition is true
Conditionals make programs responsive to different situations.
How Control Flow Fits in Programming
Control flow connects many core concepts:
- variables and data types
- logical expressions
- program behavior
Almost every non-trivial program uses control flow in some form.