Member-only story
Branching
When an "algorithm" makes a choice to do one of two (or more things), this is called branching. The most common programming "statement" used to branch is the "IF" statement.
The If Statement
Algorithms in computer programs are much like recipes, but most recipes don't let the cook make choices. If it says mix two eggs with a cup of flour, that is exactly what you do. However, some recipes do allow for variations. Such as if you are cooking on the grill outside, then do one thing, and if you are cooking in the oven inside, then do something else.
In a computer program, the algorithm often needs to make a decision about one of two things depending on the "state" of the program. The grade is greater than 90, so give him an A; otherwise, if the grade is greater than 80, give him a B,. etc.
The most common way a program makes a decision is with the "IF" statement. The statement looks like:
Matlab Version C, Java, ActionScript Version
% If Statement in Matlab. Note: "something is true" must be an
% expression (or variable) that evaluates to (or holds) a true or false
% boolean value.
If something is true )
do this code;
do all code before the end or else;
do not do anything in the else "block" of code.
else
% if something is false (NOTE: we don't have to test this).
do other code;
end
The ELSE statement
The else statement above is optional. If "nothing" is to be done when the condition is false, then the else statement should not be used! For instance, below we only…