Search code examples
matlabfortranconventionsdo-while

difference between dowhile and do while in fortran90


In a f90 code there is the following section of a code

dowhile: do while <conditions>


 ....

end do dowhile 

I never came across with such a loop, and I cannot understand what would be the difference if i omit the "dowhile ... end dowhile" and simply use a normal "do while" loop.

Can anybody here help me to clarify this point ?

If i have to convert this loop into a matlab, does the simple matlab while loop be sufficient ?

Many thanks


Solution

  • Okay, now I think I got your question:

    the dowhile: statement gives a label or name to the loop, and consequently the loop called dowhile is terminated using the enddo statement. You could have used a different name for the loop as well:

    mainloop: do while <conditions>
      ! ...
    enddo mainloop
    

    This labeling is optional, you can leave it away.

    The comments put up a good point: The use of exit or cycle with a label. You could prematurely exit or cycle the loop if it has a label. This is especially useful for nested loops:

    outer: do while <condition>
      do i=1,10
        if <some condition> then
          cycle ! cycles the inner loop
        elseif <some other condition> then
          cycle outer ! cycles the outer loop
        endif
      enddo ! i
    enddo outer
    

    If such constructs are used, you cannot easily remove the loop names.

    I don't think Matlab allows labeling loops, but I'm no expert on Matlab.


    Original answer:

    Well, the do while construct is essentially an infinite loop that is terminated if the <conditions> are true.

    conv = .false.
    do while ( conv .eqv. .true. )
      ! ... do stuff
    enddo
    

    corresponds to

    conv = .false.
    do
      if ( conv .eqv. .true. ) exit
      ! ... do stuff
    enddo
    

    This should be doable in Matlab as well. The Matlab syntax is (taken from here):

    while expression
       statements
    end
    

    As a side-note: I would define a simple do-loop as a finite loop, though...

    do i=1,10
      ! ... do stuff
    enddo ! i
    

    This construct is not equivalent to the do while-loop.