Fortran - Constants

The constants refer to the fixed values that the program cannot alter during its execution. These fixed values are also called literals.

Constants can be of any of the basic data types like an integer constant, a floating constant, a character constant, a complex constant, or a string literal. There are only two logical constants : .true. and .false.

The constants are treated just like regular variables, except that their values cannot be modified after their definition.

Named Constants and Literals

There are two types of constants −

  • Literal constants
  • Named constants

A literal constant have a value, but no name.

For example, following are the literal constants −

Type Example
Integer constants 0 1 -1 300 123456789
Real constants 0.0 1.0 -1.0 123.456 7.1E+10 -52.715E-30
Complex constants (0.0, 0.0) (-123.456E+30, 987.654E-29)
Logical constants .true. .false.
Character constants

"PQR" "a" "123'abc$%#@!"

" a quote "" "

'PQR' 'a' '123"abc$%#@!'

' an apostrophe '' '

A named constant has a value as well as a name.

Named constants should be declared at the beginning of a program or procedure, just like a variable type declaration, indicating its name and type. Named constants are declared with the parameter attribute. For example,

real, parameter :: pi = 3.1415927


The following program calculates the displacement due to vertical motion under gravity.

program gravitationalDisp

! this program calculates vertical motion under gravity 
implicit none  

   ! gravitational acceleration
   real, parameter :: g = 9.81   
   ! variable declaration
   real :: s ! displacement   
   real :: t ! time  
   real :: u ! initial speed  
   ! assigning values 
   t = 5.0   
   u = 50  
   ! displacement   
   s = u * t - g * (t**2) / 2  
   ! output 
   print *, "Time = ", t
   print *, 'Displacement = ',s  
end program gravitationalDisp

When the above code is compiled and executed, it produces the following result −

Time = 5.00000000    
Displacement = 127.374992    
Kickstart Your Career

Get certified by completing the course

Get Started