while

First introduced in version: 3.00.6

Syntax

while(conditions){
    statements
}

Details

The while loop repeatedly executes a block of code as long as the specified condition is true.

Note:

  • conditions must be enclosed in parentheses ().
  • When the loop body contains only one statement, braces can be omitted. When there are multiple statements, braces must be used; otherwise, an error will be reported.
  • If conditions is NULL or !NULL, it is treated as false.

The while loop evaluates the condition before executing the loop body, so the loop body may not be executed at all. The do-while loop executes the loop body before evaluating the condition, so the loop body is executed at least once. For details, see do-while.

Examples

// Sum integers from 1 to 100
s = 0
x = 1
while (x <= 100) {
    s += x
    x += 1
}
print s
// output: 5050

continue is used to skip the remaining statements in the current iteration and proceeds to the next iteration of the loop. When using continue in a while loop, the increment statement (x += 1) must be placed before continue; otherwise, an infinite loop may occur.

x = 0
while (x < 10) {
    x += 1
    if (x % 2 == 0) continue
    print x
}
// output:
// 1
// 3
// 5
// 7
// 9

while loops can be nested and can also be used together with do-while and for loops.

// Print the multiplication table
i = 1
while (i <= 9) {
    j = 1
    while (j <= i) {
        print(i + " * " + j + " = " + (i * j))
        j += 1
    }
    i += 1
}

// Generate a 5x5 random matrix
// The following output is for illustration only. Actual results vary because of randomness.
matrix = rand(0..9, 25)$5:5
print "Original matrix:"
print matrix

// Use while to iterate through rows and for to process columns: sum elements in each column
row = 0
while (row < matrix.rows()) {
    sum = 0
    for (col in 0:matrix.cols()) {
        val = matrix[row][col]
        if (val != 0) sum += val
    }
    print "Sum of elements in column " + (row+1) + ": " + sum
    row += 1
}

Note:

  • Avoid infinite loops: variables involved in the loop condition must be modified in the loop body; otherwise, the loop cannot terminate.
  • When the loop body contains only one statement, braces can be omitted. When there are multiple statements, braces must be used; otherwise, an error will be reported.