7.4.1: Compound if, elseif Logic Examples
- Page ID
- 89058
When we want to test if a variable is between 2 values, we can use compound if or elseif logic, as shown in the example below.
if (x<0) %
z = 100;
beep
% The next elseif statement determines if x is between 0 and 10 with compound logic.
% Both (x>=0) and (x<10) have to be true.
elseif ((x>=0) & (x<10))
z = 200;
beep
pause(0.6) % wait 0.6 seconds between beeps)
beep
else % For any other value of x, z is set to 0 and no beeps are made.
z = 0;
end
z % Show the value of z
Solution
Sample case 1: x = -5
Output: z = 100 with 1 beep
Sample case 2: x = 5
Output: z = 200 with 2 beeps
Sample case 2: x = 15
Output: z = 200 with no beeps.
.
% Body Temperature version 1
% Normal body temperatures are between 36.1°C and 37.2°C
% https://medlineplus.gov/ency/article/001982.htm
% For this script, the user will input their body temperature:
body_temp = input('Enter your body temperature in degrees C: ')
if ((body_temp < 36.1) | (body_temp > 37.2))
disp('Your body temperature is outside the normal range.')
if (body_temp < 36.1)
disp('It is lower than normal.')
else
disp('It is higher than normal.')
disp('You may have an infection or illness.')
end
else
disp('Your body temperature is normal.')
end
Solution
Add example text here.
.