MATLAB: How to use if statements to determine a grade

if statement

I'm asked to write a program that accepts values from 0 to 100 that will display the corresponding letter grade given the following: A=x>=90 B=x>=80 C=x>=70 D=x>=60 F=<60
For the first part I can ONLY use nested 'if' statements. The second part allows you to you else/elseif which is much easier. So far I have the following, but instead of stopping at the correct statement it continues to display each grade.
prompt='What is the grade from 0 to 100?';
x=input(prompt)
if x>0
x>=90
disp('A')
if x>0
x>=80
disp('B')
if x>0
x>=70
disp('C')
if x>0
x>=60
disp('D')
if x>0
x<60
disp('F')
end
end
end
end
end

Best Answer

There are a couple mistakes in your code. One is syntactical. When you write
if x>0
x>=90
that is not checking the two conditions x>0 and x>=90. Rather, it is checking the first condition, and simply displaying whether the second condition is true. That's why you get
ans =
logical
1
as part of your output. Instead, you need to write
if x>0 && x>=90
to check both conditions.
The second mistake is conceptual. Suppose the score is 93. You will meet the condition x>=90, so you will display "A". But then the code will continue along, and you will also meet the condition x>=80, so you will also display "B". (You have not told MATLAB to stop, or otherwise limited that case.)
Since this is presumably homework, I'll let you figure out a way to fix that.