Variable N-Level Nested Do Loops

October 2024

Variable n-level nested do loops are often considered needed or useful in solving n-dimensional problems such as those treated in Sensor and SensorOpt, but can be difficult to program directly1.   N-level do loops are easily transformed to a single loop in any programming language.  We demonstrate for Fortran.

Consider general n-level nested do loops of the form:

DO IX(1) = 1, NX(1)

    DO IX(2) = 1, NX(2)

        .....

           DO IX(N) = 1, NX(N)

               perform operations on F(IX(1),IX(2), ..., IX(N))

           ENDDO

        .....

    ENDDO

ENDDO

The equivalent single loop is constructed as follows:

 

NT = NX(1)

DO  I = 2, N

  NT = NT * NX(I)

ENDDO

 

DO K=1,NT

    M = K

    DO  I = N,1,-1

        NN = NX(1)

        DO  J = 2, I - 1

            NN = NN * NX(J)

        ENDDO

         IX(I) = (M-1) / NN + 1

         M = M - (IX(I) - 1) * NN

    ENDDO

    perform operations on F(IX(1),IX(2), ..., IX(N))

ENDDO

   

1 Skordalakis, E. and Papakonstantinou, G, "A Control Structure for a Variable Number of Nested Loops", The Computer Journal, 25, No. 1, 1982, p. 48-51.


© 2000 - 2024 Coats Engineering, Inc.