Fortran
Subroutines and Functions
Define reusable procedures in Fortran.
By EZ4Code Team
subroutinefunctionprocedure
Code
! Function with intent
function square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
end function
! Subroutine with intent(out) — modifies argument
subroutine swap(a, b)
real, intent(inout) :: a, b
real :: temp
temp = a; a = b; b = temp
end subroutine
! Pure function (no side effects)
pure function norm(vec) result(n)
real, intent(in) :: vec(:)
real :: n
n = sqrt(sum(vec**2))
end function
! Elemental — works on scalars and arrays
elemental function deg2rad(deg) result(rad)
real, intent(in) :: deg
real :: rad
rad = deg * 3.14159265 / 180.0
end function
! Usage
print *, square(5.0) ! 25.0
call swap(x, y) ! modifies x and y
print *, norm([3.0, 4.0]) ! 5.0
print *, deg2rad([0.0, 90.0, 180.0]) ! array version (elemental)Explanation
intent(in) is input (read-only), intent(out) is output (overwritten), intent(inout) is both. pure functions have no side effects — compiler can optimize. elemental functions work on scalars and arrays element-wise (like NumPy ufuncs). Subroutines are called with call; functions return values.
More Fortran Snippets
Arrays and Vector Operations
Create and operate on arrays in modern Fortran.
Modules and Derived Types
Organize code with modules and OOP-style types.
File I/O and Formatting
Read/write files with formatted output.
OpenMP Parallelism
Parallelize loops with OpenMP directives.
Numerical: Linear Algebra (BLAS/LAPACK)
Call BLAS/LAPACK for matrix operations.
Derived Types and Pointers
Custom types with allocatable components and pointers.