What does it mean when you put Loop = 1; in a program

10 views (last 30 days)
this is just a random question but i noticed on a while loop program i was reading written by someone else that they defined
loop = 1
then when they began the while loop they started it off as while (loop). what does this do to a while loop? i usually see some condition being evaluated for while before a condition statement is presented but here im not familiar with why the while loop was used this way. this is an example of what im looking at:
loop = 1;
%initialize loop
while(loop)
statement
statement

Accepted Answer

David Hill
David Hill on 15 Apr 2020
while 1%continuous loop until broken from within
if
break;
end
end

More Answers (1)

James Tursa
James Tursa on 15 Apr 2020
This is a "forever" loop. It executes until a break statement is encountered. E.g., the general construct is
while( 1 )
% stuff
if( some condition is met )
break;
end
end
  2 Comments
Walter Roberson
Walter Roberson on 15 Apr 2020
However, it is possible that the code changes the variable named loop in order to break out of the loop.
The general form is
while condition
some code
if some condition
break
end
some more code
end
where the "if" and "some more code" might not be present.
A condition in MATLAB is anything that can be evaluated to be 0 or non-zero (and non-nan). That does not have to be a relational expression: it can be a simple variable:
need_a_valid_answer = true;
while need_a_valid_answer
how_much = input('How much to withdraw?');
if isnumeric(howmuch) && isscalar(howmuch) && howmuch >= 0
need_a_valid_answer = false;
end
end
To which you would add the knowledge that any non-zero value can be used instead of true:
remaining_tries = 5;
while remaining_tries %implicitly this is remaining_tries ~= 0
how_much = input('How much to withdraw?');
if isnumeric(howmuch) && isscalar(howmuch) && howmuch >= 0
remaining_tries = 0;
else
remaining_tries = remaining_tries - 1;
end
end

Sign in to comment.

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!