Skip to content

Latest commit

 

History

History
162 lines (130 loc) · 3.04 KB

fortran.md

File metadata and controls

162 lines (130 loc) · 3.04 KB
title description created updated
Fortran
Fortran cheatsheet contains useful code syntax with examples which is really handy while coding.
2020-06-29
2020-06-29

Sample program

program hello
  character :: name
  read *, name
  print *, "Hello ", name
end program hello
  • program : All Fortran programs start with the keyword program followed by program name
  • character :: name : declaring a character variable named name
  • read : to read the data from console
  • print : to display the data to console
  • end program : All Fortran programs end with the keyword end program followed by program name
  • ! : Comment

Data Types

Data type Description Usage
Integer To store integer variables integer :: x
Real To store float values real :: x
Complex To store complex numbers complex :: x,y
Logical To store boolean values True or false logical :: x=.True. , logical :: x = .FALSE.
Character To store characters and strings character :: x

Variables

data type :: variable_name

Example

   ! declaring variables
   integer :: marks      ! Integer variable
   character(len=30) :: name ! string variable of length 30 characters
   
   !assigning values to variables
   marks = 60
   name = "Foo"  

Derived Data types

!Type Declaration
   type typeName      
      !declarations
   end type typeName

!Declaring type variables
   type(typeName) :: type-varName

!accessing the components of the derived type
   
   type-varName%type-declaration-variable = value

Operators

Operator type Description
Arithmetic Operator + , - , * , / , **
Relational Operator < , > , <= , >=, /= , ==
Logical Operator .and. , .or. , .not. , .eqv. , .neqv.

Arrays

Syntax

data-type, dimension (x,y) :: array-name

Example

integer, dimension(3,3) :: cube

Conditional Statements

1. If

if (logical-expression) then      
   !Code  
end if

2. If-Else

if (logical-expression) then     
   !code when the condition is true
else
   !code when the condition fails
end if

3. Case

[name:] select case (regular-expression) 
   case (value1)          
   ! code for value 1          
   ... case (value2)           
   ! code for value 2           
   ...       
   case default          
   ! default code          
   ...   
end select [name]

Loops

1. Do

do i = start, stop [,step]    
   ! code
end do

2. Do-While

do while (condition) 
   !Code
end do

Function

A function is a procedure which returns a single value.

function functionName(arguments)  
  ! code 
end function [functionName]

Calling a function

functionName(arguments)  

Sub-routines

Subroutine is a procedure which does not return a value.

subroutine name(arguments)
  ! code  
end subroutine [name]

Calling a Sub-routine

call subroutineName(arguments)