gfortran 4.5.0

Version of implementation gfortran of programming language Fortran

A version of gfortran compiler.

Examples:

Factorial - Fortran (110):

This example uses iterative factorial definition. Format specifiers I and A are used for printing integers and strings, respectively. Trying to calculate 13! produces an arithmetic overflow error, so last lines of program output look like this:

13! = 1932053504
14! = 1278945280
15! = 2004310016
16! = 2004189184

    program Factorial

    integer :: f,n

    f = 1
    n = 0
    
    do
        print '(I2, A, I10)', n, "! = ", f
        n = n + 1
        f = f * n
        if (n==17) then
            exit
        end if
    end do

    end program Factorial

Fibonacci numbers - Fortran (113):

This example uses iterative definition of Fibonacci numbers. The tricky part is printing the calculated values in one line, without leading or trailing spaces. Format specifier (I3, A, $) means that first an integer is printed using exactly 3 positions, followed by a string. The final $ suppresses trailing carriage return, used by default, so that everything is printed in one line.

    program Fibonacci

    integer :: f1,f2,f3,i

    i = 1
    f1 = 0
    f2 = 1
    
    do
        f3 = f2 + f1
        f1 = f2
        f2 = f3
        i = i + 1
        if (f1<10) then
            print '(I1, A, $)', f1, ', '
        elseif (f1<100) then
            print '(I2, A, $)', f1, ', '
        else
            print '(I3, A, $)', f1, ', '
        end if
        if (i==17) then
            exit
        end if
    end do
    
    print *, '...'

    end program Fibonacci

Hello, World! - Fortran (109):

program HelloWorld

print *, 'Hello, World!'

end program HelloWorld

Quadratic equation - Fortran (475):

This example uses built-in complex data type.

program Quadratic
  integer a, b, c
  real d, p1, p2
  complex cp2

  read (*, *) a
  if (a.eq.0) then
    write (*, *) "Not a quadratic equation"
    stop
  end if
  read (*, *) b
  read (*, *) c
  d = b * b - 4 * a * c
  p1 = - b / 2.0 / a
  if (abs(d) < 1.0e-9) then
    write (*, "(A, F8.3)") "x = ", p1
  elseif (d > 0) then
    p2 = sqrt(d) / 2.0 / a
    write (*, "(2(A, F8.3))") "x1 = ", p1 + p2, char(13)//char(10)//"x2 = ", p1 - p2
  else
    cp2 = sqrt(cmplx(d)) / 2.0 / a
    write (*, "(2(A, F8.3, F8.3), A)") "x1 = (", p1 + cp2, ")"//char(13)//char(10)//"x2 = (", p1 - cp2, ")"
  end if
end