Chapter 3: Selection Statements Exercises
Chapter 3: Selection Statements Exercises
Exercises
1) What would be the result of the following expressions?
'b' >= 'c' – 1 1
3 == 2 + 1 1
(3 == 2) + 1 1
outhour = currenthour + 1;
if outhour == 13
outhour = 1;
end
end
4) Write a script to calculate the volume of a pyramid, which is 1/3 * base * height,
where the base is length * width. Prompt the user to enter values for the length, width,
and height, and then calculate the volume of the pyramid. When the user enters each
value, he or she will then also be prompted for either ‘i’ for inches or ‘c’ for centimeters.
(Note 2.54 cm = 1 inch). The script should print the volume in cubic inches with three
decimal places. As an example, the output format will be:
if den == 0
fprintf('Division by 0 not possible\n')
else
fprintf('The fraction is %.2f\n', num/den)
end
2
7) The eccentricity of an ellipse is defined as
b
1
a
where a is the semimajor axis and b is the semiminor axis of the ellipse. A script
prompts the user for the values of a and b. Since division by 0 is not possible, the
script prints an error message if the value of a is 0 (it ignores any other errors,
however). If a is not 0, the script calls a function to calculate and return the
eccentricity, and then the script prints the result. Write the script and the function.
Ch3Ex7.m
% Prompts the user for the semimajor and semiminor axes of
% an ellipse and calculates and returns the eccentricity
% (if the semimajor axis ~=0)
if a1 > a2
disp('The velocity will increase')
elseif a1 < a2
disp('The velocity will decrease')
else
disp('The velocity will remain the same')
end
10) In chemistry, the pH of an aqueous solution is a measure of its acidity. The pH
scale ranges from 0 to 14, inclusive. A solution with a pH of 7 is said to be neutral, a
solution with a pH greater than 7 is basic, and a solution with a pH less than 7 is
acidic. Write a script that will prompt the user for the pH of a solution, and will
print whether it is neutral, basic, or acidic. If the user enters an invalid pH, an error
message will be printed.
Ch3Ex10.m
% Prompts the user for the pH of a solution and prints
% whether it is basic, acidic, or neutral
if m < n
outvec = m:n;
else
outvec = m:-1:n;
end
end
12) Write a function flipvec that will receive one input argument. If the input
argument is a row vector, the function will reverse the order and return a new row
vector. If the input argument is a column vector, the function will reverse the order
and return a new column vector. If the input argument is a matrix or a scalar, the
function will return the input argument unchanged.
flipvec.m
function out = flipvec(vec)
% Flips it if it's a vector, otherwise
% returns the input argument unchanged
% Format of call: flipvec(vec)
% Returns flipped vector or unchanged
[r c] = size(vec);
if r == 1 && c > 1
out = fliplr(vec);
elseif c == 1 && r > 1
out = flipud(vec);
else
out = vec;
end
end
13) In a script, the user is supposed to enter either a ‘y’ or ‘n’ in response to a
prompt. The user’s input is read into a character variable called “letter”. The script
will print “OK, continuing” if the user enters either a ‘y’ or ‘Y’ or it will print “OK,
halting” if the user enters a ‘n’ or ‘N’ or “Error” if the user enters anything else. Put
this statement in the script first:
letter = input('Enter your answer: ', 's');
Write the script using a single nested ifelse statement (elseif clause is permitted).
Ch3Ex13.m
% Prompts the user for a 'y' or 'n' answer and responds
% accordingly, using an if-else statement
switch letter
case {'y', 'Y'}
disp('OK, continuing')
case {'n', 'N'}
disp('OK, halting')
otherwise
disp('Error')
end
15) In aerodynamics, the Mach number is a critical quantity. It is defined as the
ratio of the speed of an object (e.g., an aircraft) to the speed of sound. If the Mach
number is less than 1, the flow is subsonic; if the Mach number is equal to 1, the flow
is transonic; if the Mach number is greater than 1, the flow is supersonic. Write a
script that will prompt the user for the speed of an aircraft and the speed of sound at
the aircraft’s current altitude and will print whether the condition is subsonic,
transonic, or supersonic.
Ch3Ex15.m
% Prints whether the speed of an object is subsonic,
% transonic, or supersonic based on the Mach number
if mach < 1
disp('Subsonic')
elseif mach == 1
disp('Transonic')
else
disp('Supersonic')
end
16) Write a script that will prompt the user for a temperature in degrees Celsius,
and then an ‘F’ for Fahrenheit or ‘K’ for Kelvin. The script will print the
corresponding temperature in the scale specified by the user. For example, the
output might look like this:
Enter the temp in degrees C: 29.3
Do you want K or F? F
The temp in degrees F is 84.7
The format of the output should be exactly as specified above. The conversions are:
9
F C 32
5
K C 273.15
Ch3Ex16.m
% Converts a temperature from C to F or K
if rem(ranInt,2) == 0
fprintf('%d is even\n', ranInt)
else
fprintf('%d is odd\n', ranInt)
end
18) Write a function isdivby4 that will receive an integer input argument, and will
return logical 1 for true if the input argument is divisible by 4, or logical false if it
is not.
isdivby4.m
function out = isdivby4(inarg)
% Returns 1 for true if the input argument is
% divisible by 4 or 0 for false if not
% Format of call: isdivby4(input arg)
% Returns whether divisible by 4 or not
out = rem(inarg,4) == 0;
end
19) Write a function isint that will receive a number input argument innum, and will
return 1 for true if this number is an integer, or 0 for false if not. Use the fact that
innum should be equal to int32(innum) if it is an integer. Unfortunately, due to
round‐off errors, it should be noted that it is possible to get logical 1 for true if the
input argument is close to an integer. Therefore the output may not be what you
might expect, as shown here.
>> isint(4)
ans =
1
>> isint(4.9999)
ans =
0
>> isint(4.9999999999999999999999999999)
ans =
1
isint.m
function out = isint(innum)
% Returns 1 for true if the argument is an integer
% Format of call: isint(number)
% Returns logical 1 iff number is an integer
out = innum == int32(innum);
end
20) A Pythagorean triple is a set of positive integers (a,b,c) such that a2 + b2 = c2.
Write a function ispythag that will receive three positive integers (a, b, c in that
order) and will return logical 1 for true if they form a Pythagorean triple, or 0 for
false if not.
ispythag.m
function out = ispythag(a,b,c)
% Determines whether a, b, c are a Pythagorean
% triple or not
% Format of call: ispythag(a,b,c)
% Returns logical 1 if a Pythagorean triple
>> Reynolds
Enter a Reynolds number: 3500
The flow is in transition region
Ch3Ex21.m
% Prompts the user for the Reynolds number
% for an internal flow and prints
% whether it is laminar, turbulent, or in
% a transition region
if Re <= 2300
disp('The flow is in laminar region')
elseif Re > 2300 && Re <= 4000
disp('The flow is in transition region')
else
disp('The flow is in turbulent region')
end
Would it be a good idea to write the selection statements using switch? Why or why
not?
No, because the Reynolds number could be a real number and the ranges are too
large.
dd
22) The area A of a rhombus is defined as A = 1 2 , where d1 and d2 are the lengths
2
of the two diagonals. Write a script rhomb that first prompts the user for the lengths
of the two diagonals. If either is a negative number or zero, the script prints an
error message. Otherwise, if they are both positive, it calls a function rhombarea to
return the area of the rhombus, and prints the result. Write the function, also! The
lengths of the diagonals, which you can assume are in inches, are passed to the
rhombarea function.
rhomb.m
% Prompt the user for the two diagonals of a rhombus,
% call a function to calculate the area, and print it
if d1 <= 0 || d2 <= 0
disp('Error in diagonal')
else
rharea = rhombarea(d1,d2);
fprintf('The area of the rhombus is %.2f\n', rharea)
end
rhombarea.m
function rarea = rhombarea(d1,d2)
% Calculates the area of a rhombus given the
% lengths of the two diagonals
% Format of call: rhombarea(diag1, diag2)
% Returns the area of the rhombus
rarea = (d1*d2)/2;
end
Global temperature changes have resulted in new patterns of storms in many parts of
the world. Tracking wind speeds and a variety of categories of storms is important in
understanding the ramifications of these temperature variations. Programs that work
with storm data will use selection statements to determine the severity of storms and
also to make decisions based on the data.
23) Whether a storm is a tropical depression, tropical storm, or hurricane is
determined by the average sustained wind speed. In miles per hour, a storm is a
tropical depression if the winds are less than 38 mph. It is a tropical storm if the
winds are between 39 and 73 mph, and it is a hurricane if the wind speeds are >= 74
mph. Write a script that will prompt the user for the wind speed of the storm, and
will print which type of storm it is.
Ch3Ex23.m
% Prints whether a storm is a tropical depression, tropical
% storm, or hurricane based on wind speed
if wind < 38
disp('Tropical depression')
elseif wind >= 38 && wind < 73
disp('Tropical storm')
else
disp('Hurricane')
end
24) Hurricanes are categorized based on wind speeds. The following table shows
the Category number for hurricanes with varying wind ranges and what the storm
surge is (in feet above normal).
Cat Wind speed Storm surge
1 74‐95 4‐5
2 96‐110 6‐8
3 111‐130 9‐12
4 131‐155 13‐18
5 >155 >18
Write a script that will prompt the user for the wind speed, and will print the
hurricane category number and the typical storm surge.
Ch3Ex24.m
% Prints the category number and storm surge for
% a hurricane based on the wind speed
switch ranforce
case 0
disp('There is no wind')
case {1,2,3,4,5,6}
disp('There is a breeze')
case {7,8,9}
disp('This is a gale')
case {10,11}
disp('It is a storm')
case 12
disp('Hello, Hurricane!')
end
Ch3Ex25.m
if ranforce == 0
disp('There is no wind')
elseif ranforce >= 1 && ranforce <= 6
disp('There is a breeze')
elseif ranforce >= 7 && ranforce <= 9
disp('This is a gale')
elseif ranforce == 10 || ranforce == 11
disp('It is a storm')
else
disp('Hello, Hurricane!')
end
26) Clouds are generally classified as high, middle, or low level. The height of the
cloud is the determining factor, but the ranges vary depending on the temperature.
For example, in tropical regions the classifications may be based on the following
height ranges (given in feet):
low 0‐6500
middle 6500‐20000
high > 20000
Write a script that will prompt the user for the height of the cloud in feet, and print
the classification.
Ch3Ex26.m
% Prints cloud classification
27) Rewrite the following switch statement as one nested ifelse statement (elseif
clauses may be used). Assume that there is a variable letter and that it has been
initialized.
switch letter
case 'x'
disp('Hello')
case {'y', 'Y'}
disp('Yes')
case 'Q'
disp('Quit')
otherwise
disp('Error')
end
Ch3Ex27.m
letter = char(randi([97,122]));
if letter == 'x'
disp('Hello')
elseif letter == 'y' || letter == 'Y'
disp('Yes')
elseif letter == 'Q'
disp('Quit')
else
disp('Error')
end
28) Rewrite the following nested ifelse statement as a switch statement that
accomplishes exactly the same thing. Assume that num is an integer variable that
has been initialized, and that there are functions f1, f2, f3, and f4. Do not use any if
or ifelse statements in the actions in the switch statement, only calls to the four
functions.
>> areaMenu
Menu
1. Cylinder
2. Circle
3. Rectangle
Please choose one: 3
Enter the length: 4
Enter the width: 6
The area is 24.00
areaMenu.m
% Prints a menu and calculates area of user's choice
disp('Menu')
disp('1. Cylinder')
disp('2. Circle')
disp('3. Rectangle')
sh = input('Please choose one: ');
if sh == 1
rad = input('Enter the radius of the cylinder: ');
ht = input('Enter the height of the cylinder: ');
fprintf('The surface area is %.2f\n', 2*pi*rad*ht)
elseif sh == 2
rad = input('Enter the radius of the circle: ');
fprintf('The area is %.2f\n', pi*rad*rad)
elseif sh == 3
len = input('Enter the length: ');
wid = input('Enter the width: ');
fprintf('The area is %.2f\n', len*wid)
else
disp('Error! Not a valid choice.')
end
30) Modify the areaMenu script to use a switch statement to decide which area to
calculate.
areaMenuSwitch.m
% Prints a menu and calculates area of user's choice
disp('Menu')
disp('1. Cylinder')
disp('2. Circle')
disp('3. Rectangle')
sh = input('Please choose one: ');
switch sh
case 1
rad = input('Enter the radius of the cylinder: ');
ht = input('Enter the height of the cylinder: ');
fprintf('The surface area is %.2f\n', 2*pi*rad*ht)
case 2
rad = input('Enter the radius of the circle: ');
fprintf('The area is %.2f\n', pi*rad*rad)
case 3
len = input('Enter the length: ');
wid = input('Enter the width: ');
fprintf('The area is %.2f\n', len*wid)
otherwise
disp('Error! Not a valid choice.')
end
31) Modify the areaMenu script (either version) to use the built‐in menu function
instead of printing the menu choices.
Ch3Ex31.m
% Prints a menu and calculates area of user's choice
num = abs(num);
37) Simplify this statement:
if val >= 4
disp('OK')
elseif val < 4
disp('smaller')
end
if val >= 4
disp('OK')
else
disp('smaller')
end