CSE 1010
Chapter 4
Controlling Execution
Objectives
Evaluate logical expressions
– Boolean
– Relational
Change the flow of execution
– Diagrams (e.g., flowcharts)
– Selection: if and switch statements
– Iteration: for and while loops
2
Suppose…
Problem: Assign letter grades for course
performance:
avg >= 90 gets A
80 <= avg < 90 gets B
70 <= avg < 80 gets C
60 <= avg < 70 gets D
avg < 60 gets F
Input: list of student averages
3
Program Execution
Recall
Algorithm = a step-by-step sequence of instructions
that leads to the solution of a specific problem
Program = implementation of an algorithm in a
programming language
So far, all our scripts have executed the statements
one-by-one in order, i.e., sequentially
Is that always what we want to do?
. . . If not, we need something new…
4
Example, cont’d
if avg >= 90, then
letter = ‘A’
else …
avg >= 90?
true
false
do
other
i.e.,
if (expression is true)
execute code for true
letter = ‘A’
else
execute code for false
5
General Syntax of the IF statement
if (logical expression 1 is true)
execute code block 1
else if (logical expression 2 is true)
execute code block 2
…
else if (logical expr m is true)
execute code block m
else
Can only have ONE else
execute code block for no conditions were
true
ONLY ONE code block ever runs
6
Logical Expressions
Any collection of constants, variables,
and operators whose result is a Boolean
true or false value
MATLAB prints 1 for true, 0 for false
But you have to specify values as true or
false
Types: Boolean, relational
7
Relational Operators
<
<=
>
>=
==
~=
strictly less than
less than or equal to
strictly greater than
greater than or equal to
equal to
not equal to
8
Relational Examples
A = 3;
B = 6;
A < B
ans
1
A > B
ans
0
A == B
ans
0
A ~= B
ans
1
A = [3 2 1 7];
B = [6 5 4 3];
A < B
ans
1 1 1 0
A > B
ans
0 0 0 1
A == B
ans
0 0 0 0
A ~= B
ans
1 1 1 1
9
Logical Operators
&
|
element-wise logical AND (vectors)
element-wise logical OR (vectors)
&& logical AND (scalar)
|| logical OR (scalar)
~
unary NOT
Generally,
these are the
ones most
used in
conditional
expressions
10
Logical Examples
A = 4; % Declaration
B = -2; % Declaration
A > 2 && B < 2 % Is A greater than 2
% and is B less than -2?
ans
1
C = [3 6 9 12];
D = [2 4 8 16];
A > 2 && C > D
??? Operands to the || and && operators must
be convertible to logical scalar values.
11
Truth Table
A
B
A & B
A | B
~A
~B
False False
False
False
True
True
False
True
False
True
True
False
True
False
False
True
False
True
True
True
True
True
False
False
12
Example 1
A = 4;
B = 8;
C == (A && B > 2)
ans = 1
C == ((A && B) > 2)
ans = 0
Explanation
13
Explanation
Let’s try that …
A =
B =
C =
A^2
Ans
4;
8;
true;
= = B && C
?
Explanation
• On first glance, one may be tempted to
try it as
• (A^2) == (B && C) where one soon finds
B && C would give an error.
•
• But the == has higher precedence than
&&, so what one really has is
• (A^2 == B) && C which gives a false
result.
Example 2
A = 4;
B = 8;
C = 1
% True
A ^ 2 == B && C
ans = ?
% Can you explain?
% Note: ans = 0!
17
Operator Precedence
The precedence of operators governs the order
in which operations are performed.
… on the next slide
Operations listed on the same row are
performed from left to right.
The normal precedence of operators can be
overruled by enclosing preferred operations in
parentheses ( . . .)
… recommended to avoid errors!
Matlab Precedence of Operators
.’
.^
Scalar transpose and power
’
^
Matrix transpose and power
+ - ~
Unary operators
.* ./ .\ * / \
Multiplication, division, left division
+ -
Addition and subtraction
:
Colon operator
< <= >= > == ~=
Comparison
&
Element-wise AND
|
Element-wise OR
&&
Logical AND
||
Logical OR
The normal precedence of operators can be overruled by enclosing
preferred operations in parentheses!
19
Try These:
The test is run element-by-element on
two row vectors, A and B:
A = [2 4 6 8], B = [1 3 9 27]
C=A<B
C = [0 0 1 1]
D=A<5
D = [1 1 0 0]
E=B<5
E = [1 1 0 0]
C&D
~E
% Try in Matlab
% Try in Matlab
20
Short circuit Evaluation (on your own time)
Evaluate only as much of the expression as
needed to get the result
A && condition short-circuits to false if the left
operand evaluates to false
A || condition short-circuits to true if the left
operand evaluates to true
Example:
n =Input('Enter a index value');
% check that n is a valid index
if ( n <= length(v) && n > 0 )
…
If n is not valid , the evaluation will stop and v(n)
21
will cause an error
Flow Chart
A graphical representation of your algorithm
Show solution design (algorithm) independent of the
code implementation
Flow Chart elements:
: to begin or end a section of code
: indicates input or output processes
: indicates a decision point
: for general statements and calculations
22
Example Flow Chart
Write a program to convert from mph to ft/s
Algorithm:
Flow Chart:
• Define a vector of mph values
• Convert mph to ft/s
• Combine the mph and ft/s
vectors in to a matrix
• Create a table title
• Create column headings
• Display the table
Recommendation: Transfer the
algorithm/flowchart steps to your m-file
as comments and then add appropriate
code between the comments
Start
Define a
vector of mph
Convert mph
to ft/s
Create a table
Output
table
End
23
Flow of control
Sequential is restrictive, does not help solve
some problems (e.g., decision problems, etc.)
– Just as humans change their minds depending on
circumstances , machines should too ;-))
Selection
– Choosing to execute a particular set of
statements depending on a condition
Repetition
– Executing a set of statements more than one
time (loops).
24
Conditional Execution in General
Basic conditional execution
requires two things:
1) A logical expression, and
2) A code block
If the expression is true, the
code block is executed.
IF
condition
false
true
statements
Otherwise, execution is resumed
at the instruction following the
code block
25
Compound Conditional = Selection
if
IF
condition
elseIF
condition
elseIF
condition
else
statements1
stmts2
stmtsN
stmtsN+1
end
By introducing elseif and else, we allow the
possibility of either conditional or unconditional
execution when a test returns false.
26
MATLAB if statements
Every if statement must be completed with a
companion end statement
Shows where to pick up after executing or not
executing a conditional code block
if
IF
condition
elseIF
condition
elseIF
condition
else
statements1
stmts2
stmtsN
stmtsN+1
end
27
What Executes? What Result?
>> a = 16;
>> b = 4;
>> if (a > b && b > 6)
c = 3;
elseif (b > 5)
c = 4;
else
c = 5;
end;
>> c
28
Does This Program Work?
score = input(‘enter score: ’);
if (score > 55)
disp( ‘D’ )
elseif (score > 65)
disp( ‘C’)
elseif (score > 80)
disp( ‘B’ )
elseif (score > 93)
disp( ‘A’ )
else
disp( ‘Not good…’ )
end
29
Vector Conditionals
Because in Matlab the Focus is on arrays,
let’s see what happens when we apply a
conditional to an array
In the following slide, we use the
example of a very simple array:
a row vector
Vector Conditional Example
>> x =[4 -9 25];
>> if x < 0
disp('some elements of x are negative')
else
y = sqrt(x)
end
ans y =
2.0000
0 + 3.0000i
So . . .
5.0000
x < 0 must have been false!
31
Example, cont’d
>> x =[4 -9 25];
>> if x > = 0
disp('some elements of x are negative')
else
y = sqrt(x)
end
ans y =
2.0000
0 + 3.0000i
5.0000
So x >= 0 must have been false!
What’s happening?
32
Conditionals and Arrays:
. . . How it works
When the test if logical expression is
performed where the logical expression may
be an array, the test returns the value
“true” only if all the elements of the logical
expression are true!
But the if
>> x =[4 -9 25];
returns
>> if x < 0 x < 0 results in [0 1 0]
the value
>> x =[4 -9 25];
“false” in
>> if x >= 0 x >= 0 results in [1 0 1]
both
cases!!33
Matlab Logical Functions
Function
all(v)
any(v)
all(A)
any(A)
Operation
Returns scalar = 1 if all elements of v have
nonzero values, otherwise returns 0
Returns scalar = 1 if any element of v has a
nonzero value, otherwise returns 0
Returns a row vector, same number of columns
as matrix A, where value 1 indicates column
had all nonzero values, 0 otherwise
Returns a row vector, same number of columns
as matrix A, where value 1 indicates column
had any nonzero value, 0 otherwise
34
Switch Statement
To select one from a set of alternatives
May be used in place of multiple if-else
statements
Template:
switch <parameter>
case <case specification 1>
<code block 1>
case <case specification 2>
<code block 2>
…
case <case specification N>
<code block N>
otherwise
<default code block>
35
end
If-else versus Switch
code = 11;
switch code
if(code == 10)
case 10
disp(‘Turn equipment off’);
disp(‘Turn equipment off’);
code = 11;
elseif(code == 11)
disp(‘Caution – recheck’);
elseif(code == 13)
disp(‘Turn on fan’);
else
disp(‘Normal temperature’);
end
…
case 11
disp(‘Caution – recheck’);
case 13
disp(‘Turn on fan’);
otherwise
disp(‘Normal temperature’);
end
…
36
The Switch Statement
Formal Syntax
switch <parameter>
case <case spec 1>
<code block 1>
case <case spec 2>
<code block 2>
.
.
case <case spec N>
<code block N>
otherwise
<default code block>
end
<case specification>
must be a single value or
a set enclosed in {…}
Code block may contain any
sequence of legal
MATLAB code including
if statement, switch, or
iteration
37
Example
Write a program that converts a test
score into its equivalent letter grade.
score = input(‘Enter score out of 100: ’);
score = floor(score/10);
switch(score)
case {10,9}
letterGrade = ‘A’;
case 8
letterGrade = ‘B’;
case 7
letterGrade = ‘C’;
case 6
letterGrade = ‘D’;
otherwise
letterGrade = ‘F’;
end
fprintf(‘Your Grade is %c\n’, letterGrade);
% Cool!
38
© Copyright 2026 Paperzz