While loop question, one too many loops happens.
1 view (last 30 days)
Show older comments
I want the counter to stop counting once the value '1' is entered. If '1' is entered when running this script, the while loop runs once more before ending. I do not want this. Am I using break the wrong way, or is something else happening?
Thanks
counter=0;
y_n=0;
while y_n==0
if y_n==1
break
end
counter=counter+1
y_n= input('enter 1 or 0\n')
end
0 Comments
Accepted Answer
Walter Roberson
on 11 Oct 2016
You just tested that y_n == 0 in the while statement. It cannot have changed value by the very next statement, at which point you test whether y_n==1 . You should move the "if" to after the input() .
Question: What do you want to have happen if the user enters (for example) 2.134473 ? That is not 0 so the while condition will no longer be true, but the if y_n==1 would be false.
3 Comments
More Answers (1)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!