UNIHIVE

Study Hub UNIPORT ENG 213.1

ENG 213.1 · Computer Programming for Engineers

Functions and subroutines

Breaking programs into procedures: intrinsic and user functions, subroutines, arguments and modules.

Our notes

2 min read

Why procedures

Splitting a program into small named pieces makes it easier to write, test, reuse and read. Fortran has two kinds: functions (return one value used in an expression) and subroutines (do a task, may return several results through arguments).

A function

program flow
  implicit none
  real :: re
  re = reynolds(1000.0, 2.0, 0.05, 1.0e-3)
  print *, 'Re =', re
contains
  real function reynolds(rho, v, d, mu)
    real, intent(in) :: rho, v, d, mu
    reynolds = rho * v * d / mu
  end function reynolds
end program flow
Output: Re = 100000.0

A subroutine

subroutine resistors(r1, r2, rs, rp)
  real, intent(in) :: r1, r2
  real, intent(out) :: rs, rp
  rs = r1 + r2
  rp = r1 * r2 / (r1 + r2)
end subroutine resistors
Call it with: call resistors(6.0, 3.0, rs, rp). Results: rs = 9.0 Ω, rp = 2.0 Ω.

Arguments

  • Arguments are passed by reference: the procedure works on the caller's variables.
  • intent(in): read only; intent(out): set by the procedure; intent(inout): both. Intent lets the compiler catch mistakes.
  • The number, order and types of actual and dummy arguments must match.

Local variables and scope

Variables declared inside a procedure are local: they do not clash with names in the main program.

Modules

A module collects constants, variables and procedures to share between programs:
module constants
  implicit none
  real, parameter :: g = 9.81, pi = 3.14159265
end module constants
Then write use constants at the top of any program that needs them.

Internal, external and recursive

Procedures after contains are internal; separate ones are external (better placed in modules). A procedure marked recursive may call itself (factorial, some numerical methods).

Exams usually ask

  • Write a function for an engineering formula and call it.
  • Distinguish a function from a subroutine.
  • Explain intent(in), intent(out) and intent(inout).

Common mistake

Calling a subroutine in an expression (x = resistors(...)) or a function with CALL. Functions go in expressions; subroutines are CALLed.

Written by the UniHive team in our own words. Spotted a mistake? Tell us on WhatsApp.

Read

Watch

We link to free material and never copy it. Every link was opened by our team before it went up; video data is a rough guide at 360p.

All ENG 213.1 topics

Report

Sign in to report this. It is free.

Is this your work (a lecturer, author or publisher)? Ask us to take it down.