next up previous contents
Next: Other flow control statements Up: Flow Control Previous: The FOR loop   Contents

The WHILE loop

If you need a loop for which you don't know in advance how many iterations there will be, you can use the `while' statement.

while condition do statement

Again, if you are using this in a program you can replace statement with a block of statements - the block must end with an endwhile . You can construct condition in the same way as for an if statement.

Here is an example where we are reading data from a file, but we don't know the number of lines in advance.

infile='/nfs/see-fs-02_users/lecjm/public_html/Teaching/IDL_course/New_Course_v1/Data/larkhill_200506241022.txt'  

;Set up array with far too many rows to contain the  data 
data=fltarr(14,5000)
header=''

openr,12,infile ; open the file to read from 
readf,12,header

inputline = fltarr(7)          ; set up a variable to hold one row of the file
linecount=0                     ; variable to count lines

;;;; start while loop to read in the data
while not eof(12) do begin       ; eof becomes true when we reach the End Of
                                ; the File.
    readf,12,inputline
    data(*,linecount)=inputline
    linecount=linecount+1

endwhile
data=data(*,0:linecount-1) ; truncate array to actual length
                                         ;  of file.
close,12
The previous example with repeat was neater though (and you could use that format with while too).



John Marsham 2009-12-07