Fortran provides another form of loop for convenience, since iterating over a fixed set of values is so common. The basic structure is as follows:
do variable = start-value, end-value, stride body enddo
The stride value is automatically added to the loop variable after the body is executed during each iteration. This loop is equivalent to the following:
variable = start-value do while ( variable <= end-value ) body variable = variable + stride enddo
This loop combines the initialization, condition, and housekeeping into one line to make the code slightly shorter and easier to read. It does not allow arbitrary Boolean conditions: It only works for loops that go from a starting value to an ending value. Any or all of the values can be variables.
The stride is optional, and if omitted, defaults to 1, regardless of the start and end values.
What is the output of each of the following loops? Answers are provided at the end of the chapter.
integer :: angle ! Initialization, condition, and housekeeping do angle = 0, 359 ! Body print *, 'sine(',angle,') = ', sin(angle * PI / 180.0d0) enddo
integer :: angle ! Initialization, condition, and housekeeping do angle = 359, 0 ! Body print *, 'sine(',angle,') = ', sin(angle * PI / 180.0d0) enddo
What is one advantage and one limitation of a Fortran fixed do loop compared with a while loop?
Rewrite the square roots program from the previous section using a fixed do loop.