In Fortran, functions are a fundamental building block that allows you to encapsulate a sequence of statements and computations into a reusable unit. Functions can return a value and can be called from other parts of the program, making your code more modular and easier to maintain.
Key Concepts
- Function Definition: How to define a function in Fortran.
- Function Call: How to call a function and use its return value.
- Function Arguments: How to pass arguments to a function.
- Intrinsic Functions: Built-in functions provided by Fortran.
- User-Defined Functions: Functions created by the programmer.
Function Definition
A function in Fortran is defined using the FUNCTION keyword. The general syntax is as follows:
FUNCTION function_name(arg1, arg2, ...)
! Declarations
IMPLICIT NONE
TYPE :: function_name
! Local variables
...
! Function body
...
function_name = result
END FUNCTION function_nameExample
Let's define a simple function that calculates the square of a number:
PROGRAM main
IMPLICIT NONE
REAL :: number, result
! Assign a value to the number
number = 5.0
! Call the function and store the result
result = square(number)
! Print the result
PRINT *, "The square of ", number, " is ", result
END PROGRAM main
FUNCTION square(x)
IMPLICIT NONE
REAL :: square
REAL, INTENT(IN) :: x
! Calculate the square
square = x * x
END FUNCTION squareExplanation
- PROGRAM main: The main program block.
- IMPLICIT NONE: Ensures all variables must be explicitly declared.
- REAL :: number, result: Declares
numberandresultas real numbers. - number = 5.0: Assigns the value 5.0 to
number. - result = square(number): Calls the
squarefunction withnumberas an argument and stores the result inresult. - PRINT: Outputs the result to the console.
- FUNCTION square(x): Defines the
squarefunction with one argumentx. - REAL, INTENT(IN) :: x: Declares
xas a real number and specifies it as an input argument. - square = x * x: Calculates the square of
xand assigns it to the function namesquare.
Function Call
To call a function, you simply use its name followed by the arguments in parentheses. The function call can be used in expressions, assignments, or as part of other function calls.
Example
This calls the square function with 3.0 as the argument and assigns the result to result.
Function Arguments
Arguments can be passed to functions by value or by reference. The INTENT attribute specifies the intended use of the argument:
INTENT(IN): The argument is read-only.INTENT(OUT): The argument is write-only.INTENT(INOUT): The argument can be read and modified.
Example
FUNCTION add(a, b)
IMPLICIT NONE
REAL :: add
REAL, INTENT(IN) :: a, b
! Calculate the sum
add = a + b
END FUNCTION addIntrinsic Functions
Fortran provides a set of built-in functions known as intrinsic functions. These functions perform common mathematical and utility operations.
Examples
SIN(x): Computes the sine ofx.COS(x): Computes the cosine ofx.SQRT(x): Computes the square root ofx.
Example
PROGRAM main
IMPLICIT NONE
REAL :: angle, result
angle = 3.14159 / 4.0
result = SIN(angle)
PRINT *, "The sine of ", angle, " is ", result
END PROGRAM mainUser-Defined Functions
User-defined functions are created by the programmer to perform specific tasks. They can be as simple or as complex as needed.
Example
FUNCTION factorial(n)
IMPLICIT NONE
INTEGER :: factorial
INTEGER, INTENT(IN) :: n
INTEGER :: i
factorial = 1
DO i = 1, n
factorial = factorial * i
END DO
END FUNCTION factorialExplanation
- INTEGER :: factorial: Declares the return type of the function as an integer.
- INTEGER, INTENT(IN) :: n: Declares
nas an integer input argument. - DO i = 1, n: A loop that multiplies
factorialby each integer from 1 ton.
Practical Exercises
Exercise 1: Create a Function to Calculate the Cube of a Number
Task: Write a function named cube that takes a real number as an argument and returns its cube.
Solution:
PROGRAM main
IMPLICIT NONE
REAL :: number, result
number = 3.0
result = cube(number)
PRINT *, "The cube of ", number, " is ", result
END PROGRAM main
FUNCTION cube(x)
IMPLICIT NONE
REAL :: cube
REAL, INTENT(IN) :: x
cube = x * x * x
END FUNCTION cubeExercise 2: Create a Function to Calculate the Greatest Common Divisor (GCD)
Task: Write a function named gcd that takes two integers as arguments and returns their greatest common divisor.
Solution:
PROGRAM main
IMPLICIT NONE
INTEGER :: a, b, result
a = 56
b = 98
result = gcd(a, b)
PRINT *, "The GCD of ", a, " and ", b, " is ", result
END PROGRAM main
FUNCTION gcd(x, y)
IMPLICIT NONE
INTEGER :: gcd
INTEGER, INTENT(IN) :: x, y
INTEGER :: a, b, temp
a = x
b = y
DO WHILE (b /= 0)
temp = b
b = MOD(a, b)
a = temp
END DO
gcd = a
END FUNCTION gcdCommon Mistakes and Tips
- Forgetting
IMPLICIT NONE: Always includeIMPLICIT NONEto avoid undeclared variables. - Incorrect
INTENT: Ensure the correctINTENTattribute is used for function arguments. - Returning the Result: Make sure to assign the result to the function name before the
END FUNCTIONstatement.
Conclusion
In this section, you learned how to define and use functions in Fortran. Functions help in making your code modular and reusable. You also explored intrinsic functions and created user-defined functions to perform specific tasks. Practice writing functions to become proficient in breaking down complex problems into manageable units. In the next section, we will delve into subroutines, another essential component of Fortran programming.
Fortran Programming Course
Module 1: Introduction to Fortran
- Introduction to Fortran
- Setting Up the Development Environment
- Basic Syntax and Structure
- Writing Your First Fortran Program
Module 2: Basic Concepts
- Variables and Data Types
- Operators and Expressions
- Input and Output
- Control Structures: If Statements
- Control Structures: Loops
Module 3: Arrays and Strings
Module 4: Procedures and Functions
Module 5: Advanced Data Structures
Module 6: File Handling
Module 7: Advanced Topics
Module 8: Best Practices and Optimization
- Code Optimization Techniques
- Debugging and Profiling
- Writing Maintainable Code
- Fortran Standards and Portability
