Skip to main content

Calculate hypotenuse: example of subroutine

Hypotenuse can be calculated using following formula:

c=a2+b2c = \sqrt{a^2 + b^2}
src/16_hypotenuse_subroutine.f90
! Compile the subroutine: gfortran -c 16_hypotenuse_subroutine.f90
SUBROUTINE calculate_hypotenuse(side_a, side_b, hypotenuse)
IMPLICIT NONE

! declare the intent of dummy variables
REAL, INTENT(IN) :: side_a
REAL, INTENT(IN) :: side_b
REAL, INTENT(OUT) :: hypotenuse

REAL :: temp

temp = side_a * side_a + side_b * side_b
hypotenuse = SQRT(temp)
END SUBROUTINE calculate_hypotenuse

Compile the subroutine:

gfortran -c 16_hypotenuse_subroutine.f90
src/16_hypotenuse_program.f90
! subroutine without module
! gfortran -c 16_hypotenuse_subroutine.f90
! gfortran 16_hypotenuse_program.f90 16_hypotenuse_subroutine.o
PROGRAM hypotenuse
IMPLICIT NONE
REAL :: s1, s2, output

WRITE (*, *) 'Program to calculate hypotenuse of a right triangle'
WRITE (*, *) 'Enter length of side 1:'
READ (*, *) s1
WRITE (*, *) 'Enter length of side 2:'
READ (*, *) s2

! notice subroutine call can update values in the calling environment
CALL calculate_hypotenuse(s1, s2, output)

WRITE (*, 99) output
99 FORMAT('Hypotenuse = ', F10.4)
END PROGRAM hypotenuse

Compile main program:

gfortran 16_hypotenuse_program.f90 16_hypotenuse_subroutine.o