Docsity

Subroutines - Mechanical Engineering - Lecture Slides, Slides of Mechanical Engineering

Partial preview of the text

Download Subroutines - Mechanical Engineering - Lecture Slides and more Slides Mechanical Engineering in PDF only on Docsity!

MET 50

Sub-programs

  • Programmers prefer to break the overall task into smaller pieces.
  • Then we write individual “sub-programs” to do each task!

(B) Subroutines:

  • When using a function, we only get ONE piece of information back.
  • A subroutine is more powerful – we can get MULTIPLE pieces of information back.
  • Subroutines are often used to do manipulations involving arrays.

Examples:

  1. Given a matrix A , take the inverse of the matrix, A -1.
  2. Compute the kinetic energy of air, assuming we know the wind.
  • A SUBROUTINE has no value associated with its name.
  • All outputs are defined in terms of arguments; there may be any number of outputs.
  • A SUBROUTINE is not called into action simply by writing its name.
  • Instead, we write a CALL statement to bring it into operation.
  • The CALL statement does two things:
    • specifies the arguments
    • results in storing all the output values.

Our subroutine will be called from inside the main program via the CALL statement, as in:

CALL TWIG(x,s,c,t)

input output

We can write arguments in any order we like, e.g., instead

CALL TWIG(s,c,t,x)

And then the subroutine itself (the code) begins with the same name and argument list – in the same order, as in:

SUBROUTINE TWIG(x,s,c,t)

This equates:

x ↔ xin s ↔ ssin c ↔ ccos t ↔ ttan

Values are shared between names as above.

The subroutine code itself – after the 1 st^ line – is a stand-alone piece of code.

Example from above:

SUBROUTINE TWIG(XIN, SSIN, CCOS, TTAN) ! IMPLICIT NONE REAL :: XIN, SSIN, CCOS, TTAN ! SSIN=SIN(XIN) CCOS=COS(XIN) TTAN=SSIN/CCOS ! END SUBROUTINE TWIG

Example 2

  1. Write a subroutine to compute and return the sum of two arrays, A(M,N) and B(M,N).
  2. Let’s call it: ARRSUM
  3. Input:
    1. A, B, M, N – you will need to provide array dimensions
  4. Output:
    1. C = A + B

To add two arrays, each 20 x 40 in size, we might have:

Inside the main program…

REAL, DIMENSION(20,40) :: A, B, C INTEGER :: M, N …input/specify values of M, N, A, and B …more code… …at this point, the value of C is unknown… CALL ARRSUM(A, B, M, N, C) …this returns the value of C = A + B …more code…

How do we insert subroutine code into main code?

Same choices as with functions:

a) At end b) Internally using CONTAINS statement