10.6 The break Statement
The break
statement jumps out of the innermost while
, do-until
, or for
loop that encloses it. The break
statement may only be used within the body of a loop. The following example finds the smallest divisor of a given integer, and also identifies prime numbers:
num = 103; div = 2; while (div*div <= num) if (rem (num, div) == 0) break; endif div++; endwhile if (rem (num, div) == 0) printf ("Smallest divisor of %d is %d\n", num, div) else printf ("%d is prime\n", num); endif
When the remainder is zero in the first while
statement, Octave immediately breaks out of the loop. This means that Octave proceeds immediately to the statement following the loop and continues processing. (This is very different from the exit
statement which stops the entire Octave program.)
Here is another program equivalent to the previous one. It illustrates how the condition of a while
statement could just as well be replaced with a break
inside an if
:
num = 103; div = 2; while (1) if (rem (num, div) == 0) printf ("Smallest divisor of %d is %d\n", num, div); break; endif div++; if (div*div > num) printf ("%d is prime\n", num); break; endif endwhile
© 1996–2020 John W. Eaton
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://octave.org/doc/v6.3.0/The-break-Statement.html