Welcome to AE Resources
Converted document Converted document

FORTRAN 90+: SCOPE OF VARIABLES EXAMPLES

It is recommended to look at the numerical methods codes where the use of variables is demonstrated. An additional example is included here.
PROGRAM SCOPE
          IMPLICIT NONE
          INTEGER :: a=5,b=6,c=10, i=20
               WRITE(*,*) SUM(a,b)
               WRITE(*,*) MUL(a)
               WRITE(*,*) FACTORIAL(c)
               WRITE(*,’(SS,4(I2 /))’) a,b,c,i
          !The values of ’a’ ’b’ ’i’ and ’c’ are still 
          !a=5 b=6 c=10 i=20 at the end of the program
          
          CONTAINS
     
               INTEGER FUNCTION sum(in1,in2)
               IMPLICIT NONE
               INTEGER, INTENT(IN) :: in1, in2
                    sum= in1+in2
               END FUNCTION sum
     
          !The values of ’in1’ and ’in2’ only apply here 
          !(Local variables) and nowhere else. If used
          !outside of this function, there would be an error.
     
               INTEGER FUNCTION mul(a)
               IMPLICIT NONE
               INTEGER, INTENT(IN) :: a
                    mul= a*b
               END FUNCTION mul
     
          !Because ’b’ is a global variable, the programmer 
          !did not have to declare it again because ’b’ 
          !already exists in the program
               
               INTEGER FUNCTION factorial(c)
               IMPLICIT NONE
               INTEGER, INTENT(IN) :: c
               INTEGER :: i,fact
               fact=1
               IF (c==0 .OR. c==1) THEN
                    factorial=1
               ELSE
                     DO i=c,1,-1
                         fact= fact*i
                         factorial=fact
                      END DO
               END IF
               END FUNCTION factorial
​
          !despite already existing with a different value, ’i’  
          !can be used as a new variable here without affecting
          !the value of ’i’ in the main program unit
END PROGRAM SCOPE