Docsity

Fortran Programming Basics: Tips and Tricks, Slides of Mechanical Engineering

Partial preview of the text

Download Fortran Programming Basics: Tips and Tricks and more Slides Mechanical Engineering in PDF only on Docsity!

MET 50

Fortran programming basics (2)

A few extra things from last week…

  1. For a program written in Fortran 90, use the extension “.f90”
  • This tells the compiler: “Hey – this is a Fortran 90 code”.
  • *.f might be interpreted at Fortran 77.
  1. Real versus Integer: it is dangerous to mix real and integer variables in Fortran

Example:

REAL :: A=10.0, B=4.0, C

INTEGER :: K=4, L

C = A/B! Produces C = 10./4. = 2.

REAL :: A=10.0, B=4.0, C, D

INTEGER :: K=10, L=4, KL

C = A/B! Produces C = 10./4. = 2.

KL = K/L! Produces KL = 10/4 = 2

! Rounded down to nearest integer

D = A/L! A/L = 10.0/4 = 2.

! A/L is treated as REAL ! D is REAL and has value 2.

  1. Order of operations in Fortran:

a. Stuff inside parentheses is done first.

b. Inside parentheses, the order is:

c. Exponentiation (A**2) – right → left

  • A23 is computed as
  • A(23)=A** d. Multiplication & division: right → left

e. Addition & subtraction: right → left

Example:

X = SQRT(B2 – 4.0AC)

X = SQRT(B2 – 4.0AC)

X = SQRT(B2 – 4.0AC)

X = SQRT(B2 – 4.0AC) X = SQRT(B2 – 4.0AC)

X = SQRT(B2 – 4.0AC)

But…caution about parentheses…

Parentheses matter!!!

And…

Will not run!

Why??

Parentheses really matter!!!

Results may be printed “ugly”, such as:

We can make things a bit nicer, as in:

PRINT*, ‘value of VAR is’, VAR, ‘value of TAR is’, TAR

Would → value of VAR is 4.500000 value of TAR is 7.

We can make things better still using the WRITE command (Chapter 5)(or sooner!)

READ* statement is the simplest way to input data to a program.

In lab-02, you ran “add2.f” to add 2 numbers.

The code prompted you for two numbers.

How?

Using the READ* statement. Docsity.com

To help you see what is going on in your code, it is good practice to add some PRINT statements:

PRINT, ‘enter values for A and B’ READ, A, B

Or:

PRINT, ‘enter first number’ READ, A PRINT*, ‘enter second number’ Docsity.com

This is a style thing!

There is a more powerful READ statement – Cht. 5

  1. Next lecture?

“selective execution”

Fortran equivalent to:

“IF it’s Sunday, sleep in. ELSE, set alarm.”

  1. Next lab?

Practice finding problems with REAL and INTEGER numbers mixed.

READ* and PRINT* statements