Skip to main content

11.11) while...end Statement


  • The "while" loop is a way of iterating through a loop without knowing how many times the loop should be executed
  • As the name suggests, the "while" loop keeps iterating whilst a logical expression is satisfied. The syntax is as follows:
  • [matlab]
    while (expression)
    statement
    end
    [/matlab]
    [matlab]
    >> % Find the largest number whose square is under 1000
    >> s=0;
    >> i=0;
    >> while (s<1000)
    >> s=i^2;
    >> i=i+1;
    >> end
    >> display(num2str(i-1))
    [/matlab]

    Why do we have i-1 here?