do-enddo loops

When writing F77 codes, you will often encounter a situation in which you need to periodically repeat a certain part of your code. This occurred also in our program factorial, where we had to multiply numbers from 2 to the number whose factorial is being calculated.

Generally, each do-enddo loop starts with statement do par=from,to,step by assigning the parameter par value from. The next operation is checking whether par$\,\leq\,$to (if step>0) or par$\,\geq\,$to (if step<0). If this condition is not true, the program jumps after the do-enddo body without executing the statements inside the loop. This may occur when counting the parameter with a negative step, do i=1,5,-1, or if the step is positive (e.g. +1) but the limits are reversed, do i=5,1.

At the end of each loop, the program updates the value of par by executing par = par+step and continues, provided that par did not exceed to. Once par exceeds the value stored in to, the program exits the loop and continues in interpreting the following commands. Note that if step is omitted, F77 automatically substitutes step = 1.

Problem: Write a program which calculates and prints the values of function $(1+1/n)^n$ for $n$ from 1 to 10000 with step 100. Note that for $n\rightarrow{}\infty$ the function converges to $e$, base of the natural logarithm.

Solution:

      do n=1,1e4,100
         eval = (1+1.0/n)**n
         write(*,'("n = ", I5, ", e = ", F6.4)') 
     +        n,eval
      enddo

The loop starts by assigning n=1. In the first execution of the loop, the program calculates the magnitude of $(1+1/n)^n$ for $n=1$ which gives 2 and prints n = 1, e = 2.0000. The magnitude of n is then increased by 1. The second execution occurs with n = 2, giving n = 2, e = 2.2500. The loop finishes once n attains the value 1e4 (10000) for which the output would be n = 10000, e = 2.7183.

Roman Gröger (2015-09-23)