IF else stement with Logical OR operator problem

I was writing a program use logical OR operator in If else . I used following code:-
grade=input('enter grade of the student \n', 's');
if grade=='A'|'B'
fprintf('student''s grade is %c. excellent Job \n',grade);
elseif grade=='C'
fprintf('student''s grade is %c. well done \n',grade);
elseif grade=='D'
fprintf('student''s grade is %c. Try harder\n',grade);
else
fprintf('Invalid entry\n');
end
irrespective of what is enter, always it shows " student's grade is X . excellent Job". Matlab is not processing any else if conditions.
Kindly provide insight

 Accepted Answer

KSSV
KSSV on 19 Jul 2020
Edited: KSSV on 19 Jul 2020
You should use
strcmp(grade,'A') || strcmp(grade,'B')
Check the code:
grade=input('enter grade of the student:', 's');
if (strcmp(grade,'A') || strcmp(grade,'B'))
fprintf('student''s grade is %c. excellent Job \n',grade);
elseif strcmp(grade,'C')
fprintf('student''s grade is %c. well done \n',grade);
elseif strcmp(grade,'D')
fprintf('student''s grade is %c. Try harder\n',grade);
else
fprintf('Invalid entry\n');
end

4 Comments

thanks a lot KSSV for prompt answer.the code worked.
Could you explain why the OR logic was not functioning with string values?I just wanted to understand the reason behind it.
It suggested to use strcmp when you check whether two strings are equal or not.
Could you explain why the OR logic was not functioning with string values?
This is the "problem" of computer language, which is radical different (and arguably more logic) than human laguage.
When you (a human) read/write
grade=='A'|'B'
I believe you simply translate from human laguage
If the grade is 'A' or 'B'.
BUT the computers understand this expresion like this:
grade == ('A' | 'B') % priority of operator
('A' | 'B') is logical operator so it translates to
'A'>0 | 'B'>0
So it translate using ascii code (computer manipulates only numbers) of the chararter
65>0 | 64>0
which returns always TRUE,
meaning equivalent to
1
in computer language (remember. computer manipulates numbers and nothing else).
So you expression
grade=='A'|'B'
is interpreted by MATLAB as
grade==1
!!! Actually it inturns then translate to ascii equivalent to something like
grade == 'some strangle grade that the is not in human world'
Now this is nowhere equivalent to what you (human) think
grade equal to 'A' or 'B'
Thanks. Nice explaination. Veey well explained

Sign in to comment.

More Answers (0)

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Asked:

on 19 Jul 2020

Commented:

on 19 Jul 2020

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!