Fortran: Introduction

Setup Fortran Environment

# First check if the environment is setup
$ gcc -v                        # checks for gcc
$ gfortran -v                   # checks for gfortran
# if either one returns an error
$ sudo apt install gcc          # install gcc
$ sudo apt install gfortran     # install gfortran

Recommended IDE: VS Code with the Modern Fortran extension by Migual Carvajal.

  • Grammar Highlighting
  • Auto-completion

My First Fortran Program: Hello

! hello.f90

! A line beginning with '!' is a comment
! This line is a comment
CHARACTER NAME*20
PRINT*, 'What is your name?'    ! print* is like cout
READ*, NAME                     ! read* is like cin
PRINT*, 'Hi there, ', NAME     
END                             ! end of program

Compiling a Fortran Program

# Similar to gcc
$ gfortran -o hello hello.f90
$ ./hello

Program Layout: Program Money

! money.f90

! Fortran is case-insensitive
! No semicolon at the end of statements
program money                            ! start of program
    real balance, interest, rate         ! variable declaration

    balance = 1000                       ! assignment
    rate = 0.09
    interest = rate * balance            
    balance = balance + interest         
    print*, 'new balance: ', balance
    end program money                    ! end of program

The general structure of a simple Fortran program is as follows (items in square brackets are optional):

[program program_name]
    [statement]
    [statement]
end [program [program name]]

The following code will also compile.

! money_alternative.f90

! Actually, the only compulsory statement in Fortran is "end"
program money                            ! this line optional
    real balance, interest, rate         

    balance = 1000; rate = 0.09          ! Statements in a line separated by;
    interest = rate * &                  ! separating a statement 
    balance                              ! into multiple lines using &
    balance = balance + interest         
    print*, 'new balance: ', balance
    end                                  ! can be replaced by "end program"

Names and Variables

A Fortran identifier must satisfy the following:

  • Starts with a letter
  • Contains only letters, digits, and underscores.
  • Has maximum length of 31

Identifiers are case-insensitive.
i.e. “rate” is the same as “RATE”, “rAtE”, etc.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值