How to declare, assign values, and print variables in Fortran

A variable is a container used to store values or data. These values are stored based on the type of data or value the variable should hold. For example, some variables only hold characters, while some hold numbers.

In Fortran, the basic data types are:

  • Integer
  • Real
  • Complex
  • Logical
  • Character

Declaring a variable

Variables in Fortran are declared at the beginning of a program.

Syntax for declaring

Variable
[data-type] :: [variable-name]
  • data-type is any of the data-types of Fortan

  • variable-name is the name of your variable.

Below are the rules to follow when naming a variable in Fortran.

Variable naming convention in Fortran

  • A variable name must not be longer than 31 characters.

  • It must be made up of alphanumeric characters and underscores.

  • Variable names are case-insensitive.

Code

Declaring a variable

In the code below, we will declare the variables name, commits, and gender.

name is to accept no more than 40 characters as a value. gender takes 1 character and commits takes any whole number.

! Declaring Variables
character(len = 40) :: name  
integer :: commits
character(len = 1 ):: gender

Assigning values to variables

Here we assign values to our variables.

! Assigning values to our variables
name = "John Doe"
commits = 34
gender = "M"

Printing the values of variables

Here, we display or print our variables to the console.

! Printing our variables
print *, name
print *, commits
print *, gender

Full code

program creatingVariable
implicit none

  ! Declaring Variables
  character(len = 40) :: name  
  integer :: commits
  character(len = 1 ):: gender

  ! Assigning values to our variables
  name = "John Doe"
  commits = 34
  gender = "M"

  ! Printing our variables
  print *, name
  print *, commits
  print *, gender

end program creatingVariable

When the code above is run, the output will be shown as follows:

Free Resources