WHILE...DO
WHILE...DO loops are used to execute a statement repeatedly while a condition remains true. The WHILE...DO statement is similar to the REPEAT...UNTIL statement except that the condition is checked prior to the execution of the statement. (See Definition of True and False for details on how the "truth" of an expression is determined.)
The syntax of the WHILE...DO statement is as follows:
or
When the WHILE statement is executed, the conditional expression is tested, and if it is true, the statement following the DO is executed. Control then returns to the beginning of the WHILE statement, where the condition is again tested. This process is repeated until the condition is no longer true, at which point the control of the program resumes at the next statement.
In the WHILE statement, the subject is never executed if the condition is initially false.
Examples — WHILE...DO
The following example reads data until the end-of-file is encountered:
The subject statement can also be in the form of a block:
The next example demonstrates one way to find the first element of an array greater than or equal to a specified value assuming the array is sorted into ascending order:
array = [2, 3, 5, 6, 10] i = 0 ;Initialize index n = N_ELEMENTS(array) ;Increment i until a point larger than 5 is found or the end of the ;array is reached: WHILE (array[i] LT 5) AND (i LT n) DO i = i + 1 PRINT, 'The first element >= 5 is element ', i
IDL Prints:
The first element >= 5 is element 2Tip
Another way to accomplish the same thing is with the WHERE command, which is used to find the subscripts of the points where ARR[I] is greater than or equal to X.P = WHERE(arr GE X)
;Save first subscript:
I = P(0)