Branching causes your program to depart from a top-down statement-by-statement execution.
A method call is the most common form of unconditional branching. When the method completes, execution returns to the point where it left off.
Conditional branching enables your program to branch based on runtime conditions, typically based on the value or relative value of one or more objects or variables.
The if
construct executes a
statement if a condition is true and skips it otherwise.
When the condition in an if
statement is actually two conditions joined by an or
operator, if the first condition
evaluates to true
, the second
condition will not be evaluated at all. This is called
short-circuiting.
The if/else
construct lets
you take one set of actions if the condition tested evaluates true,
and a different set of actions if the condition tested evaluates
false.
if
statements can be nested
to evaluate more complex conditions.
The switch
statement lets
you compare the value of an expression with several constant values
(either integers, enumerated constants, or strings), and take action
depending on which value matches.
It is good programming practice for switch
statements to include a default
statement that executes if no other matches are found.
Iteration, or looping, allows you to take the same action several times consecutively. Iterations are typically controlled by a conditional expression.
The goto
statement is used
to redirect execution to another point in the program, and its use
is typically discouraged.
The while
loop executes a
block of code while the tested condition evaluates true. The
condition is tested before each iteration.
The do...while
loop is
similar to the while
loop, but
the condition is evaluated at the end of the iteration, so that the
iterated statement is guaranteed to be executed at least
once.
The for
loop is used to
execute a statement a specific number of times. The header of the
for
loop can be used to
initialize one or more variables, test a logical condition, and
modify the variables. The typical use of a for
loop is to initialize a counter once,
test that a condition is using that counter before each iteration,
and modify the counter after each iteration.