Branching is a way to make a program behave differently based on certain conditions. This is a critical part of programming because it allows If-else statements, and corresponding code blocks are the most common form of branching. When arriving at an if statement, the program evaluates its condition, represented by a boolean expression.
A boolean expression is simply one that can only be true or false. Suppose the expression evaluates to true, than the “if” code block is executed. Otherwise, this block is skipped, and the program continues. If there are any elseif blocks after the original if, and the condition is false, they are checked in order. Finally, if there is an else block and none of the if or elseif conditions are true, it is executed instead. Importantly, elseif and else blocks will only work after an if block.
Suppose you need a program that behaves differently depending on whether a variable x is positive, negative, or zero:
if x > 0
Put “x is positive” to output
elseif x < 0 Put “x is negative” to output else Put “x is zero” to output.
In the first if statement, if “x > 0” evaluates to true, x is positive. If it is not, the elseif statement checks whether x is negative. Finally, if x is neither positive nor negative, it must be zero, so the else statement executes, even though it does not explicitly check if x is zero.