fortrangfortranfortran95

Re-executing statements in Fortran 95


Sorry for the noobie question but I need some help in figuring out how to return execution back to the start of a subroutine after a logical block is done checking user input.

Program FibSequence 
Integer(2) :: n_terms
print*, "Please Enter number 0-99"
read*,n_terms
call check_term()
End Program
Subroutine check_term()

if n_terms <= 0 then 
!print stuff
read*, n_terms
return
else if n_terms > 99 then
!print stuff
read*, n_terms
return
else
print*, "you have chosen " , n_terms
end

The program executes successfully but it does not do what it should do.

I am suspecting the program enters the check then when it does that if the number is incorrectly chosen such that the number is > 99 or <= 0 then it "rereads" the n_terms for user input then returns the execution to the main program which results in the program terminating.

The result should be when the number is incorrectly chosen the sub routine is ran entirely AGAIN instead of going to the next line of execution from main - which would be end program.

Help would be appreciated thanks!


Solution

  • It should be possible to use an alternate return, but alternate return is in the list of obsolescent features. Perhaps, the easiest way to achieve what you want to do is with an infinite DO loop that exits on valid input.

    Program FibSequence 
      Integer(2) :: n_terms   ! Note, non-portable kind type parameter
      print*, "Please Enter number 0-99"
      do
         read*,n_terms
         if (n_terms > -1 .and. n_terms < 100) exit
      end do
      ! Do something with n_terms.
    End Program