Control flow¶
Simply said, control flow statements allow us to alter the execution of our programs based on certain conditions.
If, if-else, else-if & ternary operator¶
Used to control the execution based on a singular or limited amount of conditions.
Switch¶
Used to control the execution based on multiple conditions. The expression gets evaluated once and then the code with the matching case gets executed.
While & do-while loop¶
Used to keep execution certain statements while the condition evaluates to true. A common way to infinetly loop execution is to use while (true)
.
The do-while loop will execute atleast once, even if the condition is false.
For & foreach loop¶
Used when you know the specific amount of loops you would like to do.
Statement 1
: is executed (one time) before the execution of the code block. Usually this is the initialization of someindexer
.Statement 2
: defines thecondition
for executing the code block.Statement 3
: isexecuted (every time) after
the code block has been executed.
Typically a for-loop looks like this:
A foreach loop is typically used to go through a collection:
Break & continue¶
Break
: jumps out of a loopContinue
: skips one iteration and continues to the next iteration