Loop structures: Difference between revisions

Content added Content deleted
No edit summary
(Added FORTRAN 77 loops. Since most are just hacked GOTO statements, I figure it is useful to have a quick reference.)
Line 211: Line 211:





==[[Fortran]]==

===DO loop===

FORTRAN 77 only has one loop structure: the <tt>DO</tt> loop. It is very similar to the for loop of the C-style languages.

<lang fortran>C This will add the numbers from one through `N`. Naturally, the `10`
C label can be whatever label you want to use. Also note that indenting
C is optional. I indented for the sake of readability.
INTEGER I, N, TOTAL
READ (*,*) N
TOTAL = 0
DO 10 I = 1, N
TOTAL = TOTAL + I
WRITE (*,*) I, TOTAL
10 CONTINUE

C You can also control the step; this one will count backwards from `N`,
C two by two:
INTEGER I, N
READ (*,*) N
DO 20 I = N, 1, -2
WRITE (*,*) I
20 CONTINUE

C Nota bene: the two (or three) initialization values for the loop are
C only evaluated once! So, for example, this will count from one through
C ten, where it might lead to an infinite loop in other languages:
INTEGER I, J
J = 10
DO 30 I = 1, J
WRITE (*,*) I
J = J + 1
30 CONTINUE</lang>

===While loops===

FORTRAN 77 does not, semantically speaking, have <tt>while</tt> loops. However, you can easily simulate them using <tt>GOTO</tt> statements.

<lang fortran>C A while loop in FORTRAN 77 is really just a conditional with a goto.
40 IF (condition) THEN
:
:
GOTO 40
ENDIF</lang>

===Do-until and do-while loops===

<tt>Do-until</tt> and <tt>do-while</tt> loops are a little different, but also use <tt>GOTO</tt> statements.

<lang fortran>C A do-until loop is similar to the while loop:
50 CONTINUE
:
:
IF (.NOT. (condition)) GOTO 50

C A do-while loop is almost exactly the same as a do-until loop.
60 CONTINUE
:
:
IF (condition) GOTO 60</lang>

===For loops===

If you really need to have a <tt>for</tt> loop where the range can change during the loop, you can simulate that with a <tt>while</tt> loop.

<lang fortran>C This is a rewrite of the example labelled `30`, so that it actually
C will lead to an infinite loop:
INTEGER I, J
J = 10
I = 1
70 IF (I .LE. J) THEN
WRITE (*,*) I
J = J + I
GOTO 70
ENDIF</lang>


==[[Groovy]]==
==[[Groovy]]==