User Tools

Site Tools


k10:k10.3:k10.3.5:start

10.3.5 BREAK and CONTINUE

Break and Continue are special instructions within loop control structures.

  • Break cancels and exits the current loop control structure immediately. Execution of the program is continued with the next statement after the loop control structure.
  • The Continue statement causes the current loop pass to be aborted and a new pass to be started.

10.3.5.1 Example 1

A file is opened for reading. Then the contents of the file are read out line by line and each line - under certain conditions - is stored in an array:

hFile = OPEN sFilePath For Input
 
WHILE NOT Eof(hFile)          ' As long as the end of the file has not been reached ...
  LINE INPUT #hFile, sLine    ' ... reads a line from the file
  sLine = Trim(sLine)         ' ... Spaces at the end and beginning of the line are removed. 
  IF NOT sLine THEN CONTINUE  ' ... an empty line is skipped -> continue with new loop throughput
  IF InStr("#;'", Left$(sLine)) THEN CONTINUE ' ... a comment is ignored -> next ...
   ...
  aFileArray.Add(sLine)
WEND ' NOT Eof(hFile) 
CLOSE #hFile
  • It is ensured that no empty lines or comment lines are added to the file array.
  • For these two cases, the loop pass is aborted before the aFileArray.add(sLine) command and a new line is read from the file - as long as lines can still be read.

10.3.5.2 Example 2

Example 2 picks up a case in which two nested For control structures are to be left when a certain condition is fulfilled:

Dim iN, iI As Integer 
Dim bBreak As Boolean = False 
 
For iN = 0 To aArray.Max 
  For iI = 0 To Array[iN].Max 
    If iX = aArray[iN][iI] Then 
      bBreak = True 
      Break 
    Endif 
  Next 
  If bBreak Then Break 
Next
  • First the boolean variable bBreak is set to True and with Break the inner For control structure is left.
  • In the outer For control structure the value of the variable bBreak is evaluated.
  • In the case bBreak=True, the outer For control structure is also left with Break.

10.3.5.3 Example 3

In the third example, only the numbers from an array are stored in another array, which are integer cubic roots:

Private Function CubicNumbers(aArray As Integer[]) As Integer[] 
  Dim iNumber As Integer 
  Dim aResult As New Integer[] 
 
  For Each iNumber In aArray 
    If Frac(Cbr(iNumber)) <> 0 Then CONTINUE ' Skip numbers whose cubic root is not an integer
    aResult.Add(iNumber) 
  Next 
  Return aResult 
End

Download

The website uses a temporary session cookie. This technically necessary cookie is deleted when the browser is closed. You can find information on cookies in our privacy policy.
k10/k10.3/k10.3.5/start.txt · Last modified: 23.09.2023 by honsek

Page Tools