1. C OMPUTATIONAL P HYSICS
Instructor Dr. Fawaz Hrahsheh
Department of Physics
Jordan University of Science and Technology
Second Semester 2013/2014
1/7
2. SUBPROGRAMS
• Fortran codes that solve real problems often have tens of thousands
of lines.
• The only way to handle such big codes is to split them into many
smaller subprograms.
• Subprogram is a small piece of code that solves a specific well
defined subproblem.
• subprogram can be invoked several times for different inputs
during the calculations.
• Fortran has two different types of subprograms: Functions and
subroutines.
• we start the subprograms by typing contains.
2/7
3. F UNCTIONS
• Similar to mathematical functions, Fortran functions takes a set of
input variables or parameters and return a output values.
• In general, Fortran function always has a type, .i.e, real, integer etc.
• The returns values has to be stored in a variable has the same name
of the function.
• Functions are terminated by return statement instead of stop.
• Variables defined inside Function are invisible by the main body
• A function can call another function
• Only one function for each function subprogram
• General structure of a function is:
type function name (variables)
declarations
statements
return
3/7
4. E XAMPLES ON F UNCTIONS
program myfunction
implicit none
real q,r
read*,q,r
print*,f(q),g(q,r)
!---------------------contains
real function f(x)
real:: x
f=2.0-x-x**2
return
end function
!---------------------real function g(x,y)
real:: x,y,t
t=f(x)
g=x*y-y**2+f(x)
!or
g=x**2+xy**3+t-t**2/(1-t)+t**4/(1-t)**3
return
end function
end program myfunction !----------------------
4/7
5. S UBROUTINE
• The subroutine has no type.
• The body of subroutine is actually a small program and could return
more than one value
• General structure of a subroutine is:
subroutine name (input variables,output variables)
declarations
statements
return
end
5/7
6. E XAMPLES ON SUBROUTINE
program summations
implicit none
real q,r,w
read*,q
call summ(q,r,w)
print*,r,w
!---------------------contains
subroutine summ(x,y,z)
implicit none
real, intent(in)::x
real,intent(out)::y,z
integer i; real phi
phi=0
do i=1,10
phi=phi+x*(i)
enddo
y=sqrt(phi)
z=sin(y)
end subroutine summ
end program
6/7
7. C ONT..
program swaping
implicit none
real i,j
read*,i,j
print’(1x,a,I2,5x,a,I2)’,"i=",i,"j=",j
call swap(i,j)
print’(1x,a,I2,5x,a,I2)’,"i=",i,"j=",j
!---------------------contains
subroutine swap(m,n)
implicit none
real, intent(inout)::m,n
real phi
phi=m
m=n
n=phi
end subroutine swap
end program
7/7