fortrannested-loops

n nested for loops in fortran90


i have read some topics on this, but i don't quite think it answers my question. if it does then please direct me to the correct topic and i will definitely look again.

here is my problem:

i want to write a for loop which will cycle through every possible combination of an array where the array is of length 'n'.

that is, if n = 2 then my for loop would be

do i1 = 1,2
    do i2 = 1,2
         ! do stuff here
    enddo
enddo

while if n = 3 then my array would look like

do i1 = 1,3
    do i2 = 1,3
         do i3 = 1,3
             ! do stuff here
         enddo
    enddo
enddo

and so on. how would i go about writing a routine which would do this automatically by simply an an input variable 'n'?


Solution

  • if you write out the indices, what you have is an n-digit number in base n (almost - there's an offset of 1 because you are using 1-based indices in fortran). and what you are asking for is every possible value that number can take.

    in other words, if we use 0-based indices for a moment for simplicity, you have:

    so what you are asking is how to do this in the general case.

    and you can do that by using an array to hold the n digits, starting at [0,0....0]. then, within a "while" loop (which will replace your n nested for loops), try to increment the right-most entry (digit). if that is equal to n, then go back to zero and increment to the left. once you manage to increment a value without reaching n then you are "done" and can use the numbers as your indices.

    it's pretty simple - you're just adding 1 each time.

    then, for fortran's 1-based indexing, add 1 to each digit. in other words, change the above to start with 1s and move left at n+1.

    for example, for n=4: