2024 Spring ICS Week11
2024 Spring ICS Week11
SELECTION / BRANCHING
SELECTION/BRANCHING
q The flow of control is handled behind the scenes by the
MATLAB interpreter.
q MATLAB interpreter is a program running in the
background that
q reads the statements that you write and carries
them out one by one,
q allocating space for variables,
q writing values into those variables, and
q reading values from them,
q accessing elements of arrays,
q calling functions, and
q displaying results on the screen.
SELECTION/BRANCHING
q Executing the statements in the order that the
programmer wrote them is called sequential control.
q Sequential control is the most natural and the most
common sequence in any program written in any
programming language.
q A control construct is simply a method by which the
interpreter selects the following statement to be
executed after the execution of the current statement
has concluded.
SELECTION/BRANCHING
q The programmer tells the interpreter which construct to
use utilizing (or not) particular keywords.
q Now, we will introduce keywords that signal the
interpreter to base its decision as to which statement is
to be executed not only on the order in which the
statements are written but also on the values of
expressions.
q This new control construct is called selection or
branching.
SELECTION - if statements
q An if-statement is used when the programmer wishes to
have the interpreter choose whether or not to execute a
statement or set of statements on the basis of the values
of variables.
SELECTION - if statements
A block is a set of
adjacent statements,
and each block in the
figure is controlled by
a control statement.
SELECTION – if-else statements
SELECTION – if-elseif-else statements
SELECTION – if-elseif statements
q If we wanted to require a bit more thinking on the part
of the person trying to answer our question, we could
omit the else clause from our example.
SELECTION - if statements
q So far, our
examples have
selected from
among one, two,
or three blocks
of code, but any
number of blocks
can be included
by including
additional elseif
keywords.
SELECTION - The return statement
q When a return-statement is executed (in any
programming language), it halts the function in which it
appears, in this case, day_of_week, and returns control
to the caller of the function.
• When there are two or more operators of the same precedence, left-to-right
associativity is used, meaning that the order of operation is from left to right.
Parentheses can override this associativity rule also.
SELECTION - Nested Selection Statements
• We refer to the inclusion of one control construct inside another construct as
nesting: