0

Here is my sample code, made to work out how to get a while loop to end when any one of three conditions are satisfied.

I want the code to end when n = 100, but it ends at n = 301. How can I get this to end at n=100?

clear all; close all;
n = 0;
R = 0; A = 0; T = 0;    

while (R~=1) || (A~=1) || (T~=1)     
    if n == 100
        R = 1;
    end        
    if n == 200
        A = 1;
    end 
    if n == 300
        T = 1;
    end
    n=n+1;
end
1
  • Doesn't it feel like OR & AND are the wrong way around? Commented May 4, 2015 at 7:06

1 Answer 1

5

|| means or (with short circuiting). This means that your loop won't quit until all of the conditions are false.

You want to use AND, which is &&. This will mean the loop quits when at least one of the conditions is false.

ALSO (from the comments below):

Currently n will have a value of 101 when the loop finishes (because of the n=n+1 at the bottom of the loop). If it was important that the value of n was 100, then you could insert a break (info here) into the if body so that the loop quit when n = 100.

Sign up to request clarification or add additional context in comments.

2 Comments

Also might be noteworthy that the loop counter will be at 101 when the abort condition is evaluated as true.
Seconding sobek: This is only a partial answer. Maybe suggest a break?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.