BREAK Exit Execution In Loop
Section: Flow Control
Usage
Thebreak
statement is used to exit a loop prematurely.
It can be used inside a for
loop or a while
loop. The
syntax for its use is
break
inside the body of the loop. The break
statement forces
execution to exit the loop immediately.
Example
Here is a simple example of howbreak
exits the loop.
We have a loop that sums integers from 1
to 10
, but
that stops prematurely at 5
using a break
. We will
use a while
loop.
break_ex.m function accum = break_ex accum = 0; i = 1; while (i<=10) accum = accum + i; if (i == 5) break; end i = i + 1; end
The function is exercised here:
--> break_ex ans = 15 --> sum(1:5) ans = 15