Fortran nested loops with one continue
Asked Answered
C

1

5

I'm rewriting some legacy code and came across this:

  DO 4 I=1,N
   ...
  DO 4 J=1,N
   ...
4 CONTINUE

There appears to be only one CONTINUE for these two loops. Is it equivalent to this Java code?

for (int i=0; i<n; i++) {
    ...
    for (int j=0; j<n; j++) {
        ...
    }
}
Chicoine answered 1/9, 2011 at 17:9 Comment(1)
Ahh, my eyes! Haven't had to look at Fortran since college :) Wish I could help, but I just don't remember on this one...Disclaimer
A
8

I think you are correct as to what it is equivalent to. The

4 CONTINUE

is just a labeled marker for the spot where the loop ends. Using two CONTINUE statements, or even better yet using two ENDDO (if supported by your compiler) would have been much clearer.

This page http://www.math.hawaii.edu/lab/197/fortran/fort2.htm concurs, just search for "same continue".

One detail though is that I don't think your loop variable start and end values are the same in your Java code as in the Fortran code.

Anachronism answered 1/9, 2011 at 17:35 Comment(6)
Bingo. Lines are precious, so don't waste them with extra CONTINUE statements.Toby
also, while the loop start/end values are different in the two programs, as long as you're not using the i/j values explicitly (i.e. only as array indices) you'll be fine with the Fortran code starting at [1,N] and the Java code starting at [0,N).Toby
I was under the impression that Fortran array indexing started from 1?Chicoine
they do. I only mentioned the loop variable not matching the java code because I don't know how those variables are used. @Tim's comment about right. Array of N elements would be referenced using 1..N in Fortran and 1..N-1 in Java. But if the loop indexes were used for something else, then it could be an issue. It's entirely dependent on how they're being used within the loops.Anachronism
@waitinforatrain - The lower bounds of arrays is by default 1; however, both lower and upper bounds can be -n, 0, or +n, n being integer.Shopper
@hatchet has it - as long as what the code is doing is "loop through the entire array and do something to every element independent of the absolute index", it won't matter if you start counting by default at 0 (Java) or 1 (Fortran).Toby

© 2022 - 2024 — McMap. All rights reserved.