Professional Documents
Culture Documents
Lec 6
Lec 6
control structure
1
Control Structures II
2
In this lecture you will study
Nested if - else - end
If … elseif …. elseif …. end
3
Nested if Statements
4
Example-1
A postgraduate admission sytem
accepts a student application for a
Master degree if his gpa is above 3.6
and his age is below 30.
Write a program, for this system, that
reads the gpa and the age, then
displays the message ‘Admitted’ if the
student satisifies the conditions
Example-1: Analysis
Input: gpa, age
Output : message : addmitted
nothing if not
Process: check if the student can be
admitted
Example-1: Design
Read gpa
Read age
If gpa > 3.6
If age < 30
Diplay (‘ Admitted in the Master program’)
End
End
Example: code
Example-2
Write a Matlab program to determine a student’s
letter grade based on a given integer test score.
If the score is between 90 and 100, the grade is ‘A’.
If the score is between 80 and 89, the grade is ‘B’.
If the score is between 70 and 79 the grade is ‘C’.
If the score is between 60 and 69 the grade is ‘D’.
If the score is between 0 and 59 the grade is ‘F’.
9
grade = input('Please enter your grade \n’');
if(grade >= 90)
if(grade <= 100)
fprintf('A\n'); Is there
end
a way
end
if(egrade >= 80) to link
if(grade < 90) more
fprintf( 'B\n'); than one
end condition
end
together
if(grade >= 70)
if(grade < 80)
in a
fprintf('C\n'); single
end if
end statement
if(grade >= 60)
?
if(grade < 70)
fprintf('D\n');
end
end
if(grade >=0 )
if(grade < 60)
fprintf('F\n');
end
end
If with Logical Operators
if (grade >= 90 && grade <= 100)
fprintf('A \n‘);
end
if (grade >= 80 && grade < 90)
fprintf('B \n‘);
end
if (grade >= 70 && grade < 80)
fprintf('C \n‘);
end
if (grade >= 60 && grade < 70)
fprintf('D \n‘);
end
if (grade >= 0 && grade < 60)
fprintf('F \n‘);
end
11
Nested If-else Statement
S T
Else
End
Else
Diplay (‘Not admitted’)
End
Example-3: code
Example-4
A Blood test device that measures the sugar level classify and
display the state of the patient as follows
25
If-elseif Statement
Equivalent to if-else,
But:
-Does not require an end for each if
26
If-elseif Statement
27
Exercise 1
Write a Matlab program that prompt the
user to input three numbers then output
the maximum one.
1. Your code should not use the logical && or ||
28
Exercise 2
Write a program that read the temperature
(T) then displays
'Hot' if T > 45
'Warm' if 30 < T <= 45
'Cool' if 18 < T <= 30
'Cold' if 0 < T <= 18
'Out of range, otherwise
29