MESA Summer School 2019: Fortran Examples
Table of Contents
Fortran Examples
Here are a few quick examples of Fortran in action. This should be mostly sufficient to get you through the summer school.
Variables
Declaring Variables
! declare a boolean variable logical :: flag ! declare an integer variable integer :: i ! declare a double precision variable real(dp) :: foo ! declare a 1d array with 10 elements real(dp), dimension(10) :: bar
Assigning Variables
! booleans have two special values flag = .true. flag = .false. ! arrays are 1-indexed (using parentheses) bar(1) = 3.14 bar(2:9) = 0 bar(10) = 2.72
Logic
Comparison Operators
There are two (equivalent) forms of comparison operators in Fortran
| text form | symbol form | description | 
|---|---|---|
| .gt. | > | greater than | 
| .lt. | < | less than | 
| .ge. | >= | greater than or equal to | 
| .le. | <= | less than or equal to | 
| .eq. | == | equal to | 
| .ne. | /= | not equal to | 
! these are the same (i .ne. 0) (i /= 0)
Logical Operators
There are three logical operators: .and., .or., and .not..
! true when 0 < i < 10 ((i > 0) .and. (i < 10)) ! true when i /= 0,1 (.not. ((i .eq. 0) .or. (i .eq. 1)))
If-Then-Else
! here is an example of how to do some logic if (x .gt. 0) then heavyside = 1.0 else if (x .lt. 0) then heavyside = 0.0 else heavyside = 0.5 end if
Loops
! here is an example of a do loop array(1) = 1 array(2) = 1 do i = 3, 10 array(i) = array(i-1) + array(i-2) enddo