Home > Net >  Statement label in ENDDO not matching DO label
Statement label in ENDDO not matching DO label

Time:12-07

I wrote a program to check if a number is prime or not.

Here is the code:

program prime
integer n,i
print *, 'enter a number'
read *,n
do 10,i=2,n-1
    if(mod(n,i).eq.0.0) then
        print*, 'it is not prime'
        read*
        stop
    end if
continue
if(n.eq.i)print *, 'it is prime'
read *
stop
end do
end program

However, there was a problem. I got an error:

Error: Statement label in ENDDO doesn't match DO label

The error in itself was understandable, the end do was not connected with the do loop. However, I cannot connect it as the program will not let me do so. Why is this?

CodePudding user response:

With the statement

do 10,i=2,n-1

you are introducing a labelled DO construct. A labelled DO construct needs an appropriate termination statement, with matching label. In current Fortran, a matching labelled DO construct is terminated with

10 end do

or

10 continue

Labelled DO constructs are obsolescent in current Fortran, so the entire DO construct of the question can instead be written as

do i=2,n-1
   ...
end do

In the question, there is horribly confusing indentation. The continue statement is perhaps intended as the termination of the loop, but it isn't because it isn't labelled 10. continue is just a normal, do nothing, statement which has significance as a loop termination only through its label. Instead, the compiler sees the loop terminated by the end do, regardless of indentation, and then complains because it's missing the appropriate label.

The logic of the loop agrees with the indentation: the continue statement should be the end of the loop. There are three options

  1. add a label 10 to the statement
  2. change the continue to 10 end do
  3. remove the 10 from the DO statement and change continue to end do

For each option, also delete the second end do.

Finally, with

if(n.eq.i) ...

coming after the loop, that condition is redundant: i will always have value n if it's reached.

  • Related