FUNCTION: a self-contained subprogram invoked in an expression that returns a single numeric value (F)

⇒Home ⇒Contents ⇒more on Programming

⇒ Example of a FUNCTION call in "Factorial" (RosettaCode)
 ! the "main" program does not have an extra declaration
REAL :: n=5, k=2 ! 2 global variables

nplusk = SumGlobals() ! returns 7 anotherGlobalVariable ! was created in SumGlobals and is 25
binomial_coefficient = Binomial(n, k) ! returns 10
inserted = FillString(" a b c") ! returns 166667 blanks = count_blanks() ! returns 5E5 longstring ! a numeric scalar of value 0 (default). The declaration in FillString is not known here END
 FUNCTION SumGlobals()
    ! without dummy arguments or USE all variables are global
    SumGlobals = n + k ! function result, evaluates to 7
    anotherGlobalVariable = n^k ! global variable, evaluates to 25
 END
 
 FUNCTION Binomial(n, k) ! calls the function Factorial
    Binomial = Factorial(n) / Factorial(k) / Factorial(n-k)
 END
 
 FUNCTION Factorial(n) ! all variables local to this function:
    ! numeric scalar dummies do not require a declaration
    Factorial = 1
    DO i = 2, n   ! i is local, n is a dummy argument
      Factorial = Factorial * i ! factorial function value
    ENDDO
 END
 
 FUNCTION FillString(text)
 ! with procedure arguments any variables remain local to this function
 CHARACTER text, longstring*1E6 ! a dummy and a 1-megabyte string
    FillString = EDIT(Text=longstring, End, Insert=text, DO=1E6)
 END
 
 FUNCTION count_blanks()
 USE FillString: longstring ! import a variable
 ! with USE any variables remain local to this function
    count_blanks = EDIT(Text=longstring, End, Count=" ")
END
 

How your donation will be used, and how to get a HicEst key code in return


©2000-2010 Georg Petrich, HicEst Instant Prototype Computing. All rights reserved.
Impressum