Docsity

Sub-programs - Mechanical Engineering - Lecture Slides, Slides of Mechanical Engineering

Partial preview of the text

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

MET 50

Sub-programs

  • The codes we/you have written so far are teeny (10- lines).
  • In science & engineering, many codes are huge.
  • Thousands of lines of code.

Example:

  • To make a weather forecast….
  • We need to pay attention to:
  1. Solar radiation heating – compute in one code
  2. Longwave radiation cooling – compute in one code
  3. Cloud cover – compute in one code
  4. Evaporation from the ocean – compute in one code
  5. etc etc.
  • It makes sense to write a separate chunk of code for each task!
  • Makes initial development easier
  • Allows upgrades easily
  • In BOTH cases, we:
  1. Send some information from the main program to the sub-program
  2. The sub-program does some calculation(s)
  3. The sub-program returns an value to the main program.

(A) Functions:

  • We have already met intrinsic functions.
  • Built in to the Fortran compiler.
  • Things like “sin(x)”

When we write: Y = SIN(X), our code is calling an (intrinsic) function.

FUNCTION name (arguments) Usual Fortran statements Execution statements RETURN END FUNCTION name

  • name has to obey usual rules
  • “arguments” are values sent over from the main program
  • “RETURN” statement sends results back to the main program

Example:

FUNCTION f_to_c (Temperature) ! or… REAL FUNCTION f_to_c (Temperature) ! ! Input: Temperature = temp in deg F ! Output: f_to_c = temp in deg C ! IMPLICIT NONE REAL :: f_to_c, Temperature ! f_to_c = (Temperature - 32.0)*9./5. ! RETURN END FUNCTION f_to_c

So:

  1. YOU get to decide which pieces of code to assign to a function.
  2. YOU get to write the code for that function.
  3. YOU get to put code in the MAIN PROGRAM which gets information from the function.

And:

  1. YOU get to decide where to put the “function code”.
  2. ???

There are two places we can put the “function code”:

  1. At the end of the main code/after the main code.
  2. At the end of the main code/inside the main code.

Going back to our TEMPCON and f_to_c example…

  1. At the end of the main code/inside the main code. PROGRAM TEMPCON IMPLICIT NONE REAL :: TEMPIN, TEMP PRINT,’ENTER A TEMPERATURE IN DEGREES F:’ READ,TEMPIN TEMP =f_to_c(TEMPIN) PRINT,TEMPIN,TEMP CONTAINS ← new KEYWORD FUNCTION f_to_c (Temperature) ! Input: Temperature = temp in deg F ! Output: f_to_c = temp in deg C IMPLICIT NONE REAL :: f_to_c, Temperature f_to_c = (Temperature - 32.0)9./5. RETURN END FUNCTION f_to_c END PROGRAM TEMPCON
  1. Main code could look like: PROGRAM MAIN IMPLICIT NONE REAL :: bla bla bla whatever CONTAINS ← new KEYWORD FUNCTION sub1 (X1) bla bla bla RETURN END FUNCTION sub FUNCTION sub2 (X2) bla bla bla RETURN END FUNCTION sub etc. END PROGRAM MAIN