Conditional Execution


Motivating example

Write a MATLAB program that simulates rolling a 6-sided die 1000 times and counts the number of times a 3 showed up on top.

% initialize a counter

% for 1000 rolls

    % roll the die
	
    % if a 3 was rolled
        % increment the counter
	

Relational and logical operators

Boolean values

In MATLAB:

 

Relational operators

In MATLAB:

 

 

Logical (boolean) operators

NOT
AND
OR

Short-circuit AND (&&) and OR (||)

*
*

a && b : if a is __________ , then skip looking at (evaluating) b — the result is __________

 

a || b : if a is __________ , then skip looking at (evaluating) b — the result is __________

 

Example:

 

 


Selection using if statements

Basic if statement

if boolean_condition
    statements to execute if boolean_condition is true
end

Example:

 

 

 

 

 

 

if-else statement

if boolean_condition
    statements to execute if boolean_condition is true
else
    statements to execute if boolean_condition is false
end

Example:

% ask user if it is raining


% if the user says "yes"
   
    % set isRaining to true (i.e., 1)
  
      
% otherwise (else)
   
    % set isRaining to false (i.e., 0)
   
 

 

What if we use :

Option 1:

 

Option 2:

 

Option 3:

 

if-elseif-else statement

if bool_cond1

    statements to execute if bool_cond1 is true
	
elseif bool_cond2

    statements to execute if bool_cond2 is true
	
elseif bool_cond3

    statements to execute if bool_cond3 is true
	
else

    statements to execute if none of the boolean conditions is true
	
end

Example: see if-elseif-else example at end of handout


Iteration using while loop

while boolean_condition

    statements to execute if boolean_condition is true
	
end

Example: count how many rolls it takes in order to get 10 3's.

% initialize counter for # of 3's seen and # of rolls



% while we haven't seen 10 3's

   
    % roll die
    
    
    % increment roll counter

   
    % if a 3 is on top, increment 3's counter
   
    
    
 
 
    
% display results


                   
     

if-elseif-else Example

An unnamed CS 310 student uses the following (not recommended) rubric to determine whether to procrastinate on a particular assignment:

Suppose that the following variables have been given values:

Write MATLAB code that sets the variable procrastinate to true (1) if the student should decide to procrastinate and sets procrastinate to false (0) otherwise.

Method 1: use if-elseif-elses

 

 

 

 

 

 

 

 

 

 

 

Method 2: use only one if-else

 

 

 

 

 

Method 3: use no ifs