In this case, if the input to n is 5, the READ(*,*) statement in the DO-loop executes 5 times. Each time this READ(*,*) is executed, it reads in one line and consumes the first integer value of that line. Therefore, excluding the input for n, five input lines are required.INTEGER, DIMENSION(1:10) :: x INTEGER :: n, i READ(*,*) n DO i = 1, n READ(*,*) x(i) END DO
However, the implied DO can simplify this greatly. Consider the following example:
If the value of n is 5, the implied DO in the READ(*,*) is expanded toINTEGER, DIMENSION(1:10) :: x INTEGER :: n, i READ(*,*) n READ(*,*) (x(i), i=1, n)
Therefore, the READ(*,*) statement is actually equivalent tox(1), x(2), x(3), x(4), x(5)
So, what is the difference? This is simple. Recall that the execution of a READ(*,*) would consume at least one input line. As a result, the above READ(*,*) with implied DO can read in all five numbers on a single input line rather than on five separate lines. Moreover, this READ(*,*) can also read in the input on five separate lines, since Fortran will automatically search for the next input value. Consider the following two input files:INTEGER, DIMENSION(1:10) :: x INTEGER :: n, i READ(*,*) x(1), x(2), x(3), x(4), x(5)
and the following two READ(*,*)s:File #1 File #2 ------- ------- 5 5 10 10 30 20 40 50 30 20 40 50
READ #1 can certainly reads in File #1 correctly. The result isREAD #1 READ #2 ======= ======= INTEGER,DIMENSION(1:10) :: x INTEGER,DIMENSION(1:10) :: x INTEGER :: n, i INTEGER :: n, i READ(*,*) n READ(*,*) n DO i = 1, n READ(*,*) (x(i), i=1, n) READ(*,*) x(i) END DO
n | x(1) | x(2) | x(3) | x(4) | x(5) |
5 | 10 | 30 | 20 | 40 | 50 |
Using READ #2 to read File #1 would get the same result. But, READ #1 will be able to read File #2. For READ #1, n still receives 5. Then, to read in value for x(1), a new line which contains all five integers is read. Since only x(1) needs a value, 10 is retrieved and all remaining values are ignored! When the DO loops back to read value for x(2), there is no input value in the input and an error occurs!
It is interesting to remind you that the following READ #3 can successfully read in File #1 and File #2. Why?
READ #3 ======= INTEGER, DIMENSION(1:10) :: x INTEGER :: n, i READ(*,*) n, (x(i), i=1, n)
The first WRITE(*,*) is executed five times. Each time, it reads in two integers, one for x(i) and the other for y(i). Thus, the output is on five different lines.INTEGER, DIMENSION(1:10) :: x, y INTEGER :: n = 5, i DO i = 1, 5 WRITE(*,*) x(i), y(i) END DO WRITE(*,*) (x(i), y(i), i=1, n)
The second WRITE(*,*) is equivalent to
Therefore, the ten output values are on the same line.INTEGER, DIMENSION(1:10) :: x, y INTEGER :: n = 5, i WRITE(*,*) x(1), y(1), x(2), y(2), x(3), y(3), x(4), y(4), x(5), y(5)