multiline for loop in IDL

January 2024 · 2 minute read

I am trying to do a multiline for loop in IDL but its not working, here is my first program:

for n=0,5 do begin print, n 

which gives this output:

6 

and this is my second program:

for n=0,5 do begin print, n endfor 

which gives the following error:

endfor ^ % Syntax error. 

I would like the program to gives this output:

0 1 2 3 4 5 

Thanks

3 Answers

The proper way to write a multi-line FOR loop is indeed:

for n=0,5 do begin print, n endfor 

But IDL doesn’t accept multi-line statements with BEGIN/END blocks in all contexts. For instance, not directly at the command-line. If you want to do that at the command-line, you would need to create a small main-level program by doing:

IDL> .run for n=0,5 do begin print, n endfor end 

You could also use a FOR loop like that in a procedure or function.

as @SofCh above suggests, i just use the continuation characters to do this

for n=0,5 do begin $ print, n & $ endfor 

If you're writing it in the command line you may need to add a '&' or '&$' at the end of the 'DO BEGIN' line. This indicates that the loop continues on the next line.

But also its usually easier to just condense it to one line, e.g.

 for n = 0,5 do print, n 

ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoa3FwZGuGc4GOpqylrJmhtq%2BxjJ%2Bmq2WcpLyxecinZKKcnA%3D%3D