program hello
      real*4 function urand()
      USE IFPORT;   USE IFCORE           ! базовые модули языка 
      USE ABD_INC
      USE HEADERS, dummy_urand => urand  ! объявления глобальных переменных и интерфейсов, в т.ч. интерфейса к urand. 
                                         ! Поэтому во избежание конфликта имен urand из HEADERS надо экранировать
      integer*4, save :: ini=0  ! ini - статическая переменная, сохраняется между вызовами, инициализируется один раз
      real*4 r                  ! временная переменная для баг-трекинга      
c
c     Инициализация генератора случайным числом (только 1 раз при первом вызове):
      if (ini == 0) call seed(RND$TIMESEED);    ini=1
c
 100  call random(r);           ! r должно быть значением от 0 до 1, но ФАКТ: ИЗРЕДКА СЮДА ВОЗВРАЩАЕТСЯ  r=NAN ?!?!
      if (isNaN(r)) then        ! Согласно справке фортрана, условие не должно выполняться НИКОГДА, но....
        dos_line=' Random=';  call r4_to_bit(r,dos_line(11:42))   ! Запись R4 в строку  dos_line в виде 32-битной маски
        call append(r);       call append_history()               ! Запись R4 в строку  dos_line в виде real-числа и дамп
      end if
      if (isNaN(r)) goto 100    ! В тестовой проге этот goto, естественно, закомментирован
      urand = r     ! Возвращаемое значение функции. Кто бы мог подумать, что его надо проверять...
      end
end program hello 

Fortran Online Compiler

Write, Run & Share Fortran code online using OneCompiler's Fortran online compiler for free. It's one of the robust, feature-rich online compilers for Fortran language, running on the latest version 7. Getting started with the OneCompiler's Fortran compiler is simple and pretty fast. The editor shows sample boilerplate code when you choose language as Fortran and start coding.

Read inputs from stdin

OneCompiler's Fortran online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample Fortran program which takes name as input and prints hello message with your name.

program hello
  character :: name*30
  read *, name
	print *, "Hello ", name
end program hello

About Fortran

Fortran language was initially developed for scientific calculations by IBM in 1957. It has a number of in-built functions to perform mathematical calculations and is ideal for applications which has more mathematical calculations.

Syntax help

Data Types

Data typeDescriptionUsage
IntegerTo store integer variablesinteger :: x
RealTo store float valuesreal :: x
ComplexTo store complex numberscomplex :: x,y
LogicalTo store boolean values True or falselogical :: x=.True. , logical :: x = .FALSE.
CharacterTo store characters and stringscharacter :: x

Variables

Variable is a name given to the storage area in order to manipulate them in our programs.

data type :: variable_name

Arrays

Array is a collection of similar data which is stored in continuous memory addresses.

Syntax

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

Example

integer, dimension(3,3) :: cube

Loops

1. Do:

Do is used to execute a set of statement(s) iteratively when a given condition is true and the loop variable must be an integer.

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

2. Do-While:

Do-While is used to execute a set of statement(s) iteratively when a given condition is true.

do while (condition) 
   !Code
end do

3. If:

If is used to execute a set of statements based on a condition.

if (logical-expression) then      
   !Code  
end if

4. If-Else:

If is used to execute a set of statements based on a condition and execute another set of statements present in else block, if condition specified in If block fails.

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

5. Case:

Case is similar to switch in C language.

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