Blog

Filter posts by Category Or Tag of the Blog section!

Subroutines in fortran

Friday, 24 October 2014

In Fortran, subroutines are used to group a sequence of statements together to perform a specific task or calculation. They are defined using the SUBROUTINE keyword followed by the subroutine name. Here's an example of a subroutine in Fortran:

 

PROGRAM SubroutineExample

  IMPLICIT NONE



  ! Main program

  INTEGER :: a, b, result



  ! Initialize variables

  a = 10

  b = 20



  ! Call the subroutine

  CALL AddNumbers(a, b, result)



  ! Display the result

  PRINT *, "The sum of", a, "and", b, "is", result



CONTAINS



  ! Subroutine to add two numbers

  SUBROUTINE AddNumbers(x, y, res)

    INTEGER, INTENT(IN) :: x, y

    INTEGER, INTENT(OUT) :: res



    ! Perform the addition

    res = x + y

  END SUBROUTINE AddNumbers



END PROGRAM SubroutineExample

 

In this example, we have a main program that calls a subroutine called AddNumbers. The main program declares variables a, b, and the result of type integer. It then initializes a with 10 and b with 20. The AddNumbers subroutine takes two input parameters (x and y) and an output parameter (res). The input parameters are declared with the INTENT(IN) attribute, indicating that they are read-only within the subroutine. The output parameter is declared with the INTENT(OUT) attribute, indicating that its value will be assigned within the subroutine and returned to the caller. Within the subroutine, the addition operation res = x + y is performed, and the result is stored in the res variable. After calling the subroutine, the main program displays the result using the PRINT statement.

 

Category: Software

Tags: Fortran

comments powered by Disqus