Skip to main content

4.4) for...do...endfor Statement


As in other programming languages, the FOR loop is used to execute lines of code repeatedly for a set number of times. In IDL, the FOR loop takes the form:

FOR variable = start_value, stop_value [, increment] DO statement

The [ ] in the above line indicates that the "increment" is an optional parameter. So an example of a FOR loop where we are just printing the loop variable is:

FOR I = 0, 10 DO print, I

In this case, IDL will print the numbers 0 to 10 to the screen. We can also use BEGIN and END as with the IF statement to execute a block of statements.

FOR I = 0, 10 DO BEGIN
   print, I
   print, I + 2
ENDFOR

Note that the loop variable (I in this case) will take its type from the start value. So in this example, I is an integer. If you are doing very long loops, you might want to use a long instead. You can do this by simply adding an L after the start value.

FOR I = 0L, 4000000 DO print, I