why if condition is not working in this code.
Show older comments
% code
dbstop if error
x=input('enter no1: ');
z=input('enter no2: ');
if (x<z)
disp('invalid input')
else
disp('ok')
% n=x:z;
% for i=1:n
% n;
% end
% n
end
4 Comments
dpb
on 14 Jul 2018
>> x=input('enter no1: ');
z=input('enter no2: ');
if (x<z)
disp('invalid input')
else
disp('ok')
% n=x:z;
% for i=1:n
% n;
% end
% n
end
enter no1: 3
enter no2: 2
ok
>> x=input('enter no1: ');
z=input('enter no2: ');
if (x<z)
disp('invalid input')
else
disp('ok')
% n=x:z;
% for i=1:n
% n;
% end
% n
end
enter no1: 2
enter no2: 4
invalid input
>>
Seems to work fine; what's the specific issue?
The commented-out for loop probably isn't constructed with what you intend, but there's not sufficient information provided to know what the intent is.
You may want to explore what the expression
1:n
returns for various combinations of the inputs.
Robiul Ferdous
on 14 Jul 2018
Robiul Ferdous
on 14 Jul 2018
Edited: dpb
on 14 Jul 2018
It showed exactly what you coded it to show for the given inputs--
enter no1: 5
enter no2: 1
Your code again:
x=input('enter no1: ');
z=input('enter no2: ');
if (x<z)
disp('invalid input')
else
disp('ok')
...
x <-- No1 and z <-- No2 and 5 is not less than 1 so the else block is going to be executed and that results in the 'ok' message and n never being defined.
Mayhaps if you used variable names that represent the prompts or prompts that reflect the variable names used it would be simpler to keep straight "who's who in the zoo", but the problem isn't the if (or at least a ML problem with it; you may have inadvertently written the sense of the test backwards from what you intended or somesuch).
Answers (1)
dpb
on 15 Jul 2018
As noted, perhaps the following would help...
>> x=input('enter no1: ');
z=input('enter no2: ');
if (x<z)
fprintf('\nInvalid input:\nNo 1 (x=%g) is less than No 2 (z=%g)\n',x,z)
else
disp('ok')
end
enter no1: 2
enter no2: 5
Invalid input:
No 1 (x=2) is less than No 2 (z=5)
>>
Categories
Find more on Object Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!