typestar

Functions in Fortran

A pure tip calculator: the function's name is its result variable.

program function_result
    implicit none
    print *, "tip on 48.60: ", tip(48.60, 20.0)
    print *, "tip on 12.75: ", tip(12.75, 15.0)

contains

    ! A pure function: no side effects, result named after itself.
    pure real function tip(total, pct)
        real, intent(in) :: total, pct
        tip = total * pct / 100.0
    end function tip
end program function_result

How it works

  1. pure real function tip(total, pct) promises no side effects.
  2. Both arguments are intent(in); assigning to tip sets the return value.
  3. Calls sit in expressions like any intrinsic: tip(48.60, 20.0).

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
336
Tokens
60
Three-star pace
70 tpm

At the three-star pace of 70 tokens a minute, this run takes about 51 seconds.

Type this snippet

Step 2 of 3 in Procedures, step 14 of 27 in Language basics.

← Previous Next →

Functions in other languages