### Meson setup output Source: https://fortran-lang.org/learn/building_programs/build_tools Example output from the 'meson setup' command, detailing project configuration and found tools. ```text The Meson build system Version: 0.53.2 Source dir: /home/awvwgk/Examples Build dir: /home/awvwgk/Examples/build Build type: native build Project name: my_proj Project version: undefined Fortran compiler for the host machine: gfortran (gcc 9.2.1 "GNU Fortran (Arch Linux 9.2.1+20200130-2) 9.2.1 20200130") Fortran linker for the host machine: gfortran ld.bfd 2.34 Host machine cpu family: x86_64 Host machine cpu: x86_64 Build targets in project: 1 Found ninja-1.10.0 at /usr/bin/ninja ``` -------------------------------- ### Example of setting up a container-like object and attempting I/O Source: https://fortran-lang.org/learn/oop_features_in_fortran/object_based_programming_techniques Demonstrates the initial setup of a container-like object and the compilation failure when attempting direct I/O without UDDTIO. ```Fortran type(sorted_list) :: my_list : ! set up my_list write(*, *) my_list ``` -------------------------------- ### Install FPM on Linux/WSL2 Source: https://fortran-lang.org/learn/building_programs/build_tools Steps to clone the FPM repository, navigate into the directory, and run the installation script. ```bash git clone https://github.com/fortran-lang/fpm cd fpm ./install.sh ``` -------------------------------- ### Simply Expanded Variables Example Source: https://fortran-lang.org/learn/building_programs/build_tools Example demonstrating simply expanded variables (using :=) in make, achieving the same result as the recursive example. ```makefile all: echo $(FFLAGS) include_dirs := -I./include include_dirs += -I/opt/some_dep/include FFLAGS := $(include_dirs) -O ``` -------------------------------- ### Clone the repository Source: https://fortran-lang.org/learn/building_programs/project_make Start by cloning the repository for the Fortran CSV module. ```bash git clone https://github.com/jacobwilliams/fortran-csv-module -b 1.2.0 cd fortran-csv-module ``` -------------------------------- ### CPU Time Example Results Source: https://fortran-lang.org/learn/intrinsics/system Example output from the cpu_time demonstration program. ```text Processor Time = 0.000 seconds. Processor Time = .4000030E-05 seconds. Processor Time = .2000000000000265E-05 seconds. ``` -------------------------------- ### Install g95 (OpenBSD) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs the g95 Fortran compiler, which is often used as a substitute for gfortran on OpenBSD. ```bash pkg_add g95 ``` -------------------------------- ### Install gfortran (Debian-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran This command installs the gfortran package using apt. ```bash sudo apt install gfortran ``` -------------------------------- ### Internal Procedure Example Source: https://fortran-lang.org/learn/f95_features/program_units_and_procedures An example demonstrating an internal subroutine using host association. ```fortran subroutine outer real x, y : contains subroutine inner real y y = x + 1. : end subroutine inner ! subroutine mandatory end subroutine outer ``` -------------------------------- ### dprod Example Results Source: https://fortran-lang.org/learn/intrinsics/numeric Sample output from the dprod example program. Note that results may vary between programming environments. ```text > algebraically 5.2 x 2.3 is exactly 11.96 > as floating point values results may differ slightly: > compare dprod(xy)= 11.9599993133545 to x*y= 11.96000 > to dble(x)*dble(y)= 11.9599993133545 > test if an expected result is produced > -6.00000000000000 -6.00000000000000 > PASSED > elemental > 22.9999995231628 34.0000009536743 45.0000000000000 > 22.5399999713898 25.8400004005432 24.3000004291534 ``` -------------------------------- ### Check gfortran installation Source: https://fortran-lang.org/learn/quickstart/hello_world Command to check if the gfortran compiler is installed and its version. ```bash $> gfortran --version ``` -------------------------------- ### Search for gcc versions (macOS with MacPorts) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Searches for available GCC versions that can be installed via MacPorts. ```bash port search gcc ``` -------------------------------- ### Recursively Expanded Variables Example Source: https://fortran-lang.org/learn/building_programs/build_tools Example demonstrating recursively expanded variables in make, showing how flags and include directories are handled. ```makefile all: echo $(FFLAGS) FFLAGS = $(include_dirs) -O include_dirs += -I./include include_dirs += -I/opt/some_dep/include ``` -------------------------------- ### String Array Example Source: https://fortran-lang.org/learn/quickstart/arrays_strings This example shows how to declare a character array, initialize it with strings of potentially varying lengths, and then print the elements after trimming any excess spaces. ```fortran program string_array implicit none character(len=10), dimension(2) :: keys, vals keys = [character(len=10) :: "user", "dbname"] vals = [character(len=10) :: "ben", "motivation"] call show(keys, vals) contains subroutine show(akeys, avals) character(len=*), intent(in) :: akeys(:), avals(:) integer :: i do i = 1, size(akeys) print *, trim(akeys(i)), ": ", trim(avals(i)) end do end subroutine show end program string_array ``` -------------------------------- ### Makefile Configuration and Rules Source: https://fortran-lang.org/learn/building_programs/project_make A Makefile example demonstrating configuration settings, source file lists, object file mapping, dependency generation, library creation, and executable linking. ```makefile FC := gfortran AR := ar rcs LD := $(FC) RM := rm -f GD := ./gen-deps.awk # List of all source files SRCS := src/csv_kinds.f90 \ src/csv_module.F90 \ src/csv_parameters.f90 \ src/csv_utilities.f90 TEST_SRCS := src/tests/csv_read_test.f90 \ src/tests/csv_test.f90 \ src/tests/csv_write_test.f90 # Add source and tests directories to search paths vpath % .: src vpath % .: src/tests # Define a map from each file name to its object file obj = $(src).o $(foreach src, $(SRCS) $(TEST_SRCS), $(eval $(src) := $(obj))) # Create lists of the build artefacts in this project OBJS := $(addsuffix .o, $(SRCS)) DEPS := $(addsuffix .d, $(SRCS)) TEST_OBJS := $(addsuffix .o, $(TEST_SRCS)) TEST_DEPS := $(addsuffix .d, $(TEST_SRCS)) LIB := $(patsubst %, lib%.a, $(NAME)) TEST_EXE := $(patsubst %.f90, %.exe, $(TEST_SRCS)) # Declare all public targets .PHONY: all clean all: $(LIB) $(TEST_EXE) # Create the static library from the object files $(LIB): $(OBJS) $(AR) $@ $^ # Link the test executables $(TEST_EXE): %.exe: %.f90.o $(LIB) $(LD) -o $@ $^ # Create object files from Fortran source $(OBJS) $(TEST_OBJS): %.o: % | %.d $(FC) -c -o $@ $< # Process the Fortran source for module dependencies $(DEPS) $(TEST_DEPS): %.d: % $(GD) $< > $@ # Define all module interdependencies include $(DEPS) $(TEST_DEPS) $(foreach dep, $(OBJS) $(TEST_OBJS), $(eval $(dep): $($(dep)))) # Cleanup, filter to avoid removing source code by accident clean: $(RM) $(filter %.o, $(OBJS) $(TEST_OBJS)) $(filter %.d, $(DEPS) $(TEST_DEPS)) $(filter %.exe, $(TEST_EXE)) $(LIB) $(wildcard *.mod) ``` -------------------------------- ### Example build commands Source: https://fortran-lang.org/learn/building_programs/project_make A sequence of gfortran and ar commands demonstrating how to compile Fortran source files, create a static library, and link test executables. ```bash gfortran -c -o src/csv_kinds.f90.o src/csv_kinds.f90 gfortran -c -o src/csv_parameters.f90.o src/csv_parameters.f90 gfortran -c -o src/csv_utilities.f90.o src/csv_utilities.f90 gfortran -c -o src/csv_module.F90.o src/csv_module.F90 ar rcs libcsv.a src/csv_kinds.f90.o src/csv_module.F90.o src/csv_parameters.f90.o src/csv_utilities.f90.o gfortran -c -o src/tests/csv_read_test.f90.o src/tests/csv_read_test.f90 gfortran -o src/tests/csv_read_test.exe src/tests/csv_read_test.f90.o libcsv.a gfortran -c -o src/tests/csv_test.f90.o src/tests/csv_test.f90 gfortran -o src/tests/csv_test.exe src/tests/csv_test.f90.o libcsv.a gfortran -c -o src/tests/csv_write_test.f90.o src/tests/csv_write_test.f90 gfortran -o src/tests/csv_write_test.exe src/tests/csv_write_test.f90.o libcsv.a ``` -------------------------------- ### Inquire statement example Source: https://fortran-lang.org/learn/f95_features/operations_on_external_files An example of the inquire statement to get file attributes. ```Fortran logical :: ex, op character(len=11) :: nam, acc, seq, frm integer :: irec, nr inquire (unit=2, exist=ex, opened=op, name=nam, access=acc, sequential=seq, & form=frm, recl=irec, nextrec=nr) ``` -------------------------------- ### random_seed example Source: https://fortran-lang.org/learn/intrinsics/math Sample program demonstrating the usage of random_seed to get and set a seed. ```Fortran program demo_random_seed implicit none integer, allocatable :: seed(:) integer :: n call random_seed(size = n) allocate(seed(n)) call random_seed(get=seed) write (*, *) seed end program demo_random_seed ``` -------------------------------- ### Examples Source: https://fortran-lang.org/learn/intrinsics/character Sample program demonstrating the usage of the `iachar` intrinsic function to get the ASCII code of characters and a custom `lower` function. ```Fortran program demo_iachar implicit none ! basic usage ! just does a string one character long write(*,*)iachar('A') ! elemental: can do an array of letters write(*,*)iachar(['A','Z','a','z']) ! convert all characters to lowercase write(*,'(a)')lower('abcdefg ABCDEFG') contains ! pure elemental function lower(str) result (string) ! Changes a string to lowercase character(*), intent(In) :: str character(len(str)) :: string integer :: i string = str ! step thru each letter in the string in specified range do i = 1, len(str) select case (str(i:i)) case ('A':'Z') ! change letter to miniscule string(i:i) = char(iachar(str(i:i))+32) case default end select end do end function lower ! end program demo_iachar ``` -------------------------------- ### Example Build Output Source: https://fortran-lang.org/learn/building_programs/project_make Simulated output from running 'make' on the project, showing the sequence of commands executed for dependency generation, compilation, and linking. ```text ./gen-deps.awk src/csv_utilities.f90 > src/csv_utilities.f90.d ./gen-deps.awk src/csv_parameters.f90 > src/csv_parameters.f90.d ./gen-deps.awk src/csv_module.F90 > src/csv_module.F90.d ./gen-deps.awk src/csv_kinds.f90 > src/csv_kinds.f90.d gfortran -c -o src/csv_kinds.f90.o src/csv_kinds.f90 gfortran -c -o src/csv_parameters.f90.o src/csv_parameters.f90 gfortran -c -o src/csv_utilities.f90.o src/csv_utilities.f90 gfortran -c -o src/csv_module.F90.o src/csv_module.F90 ar rcs libcsv.a src/csv_kinds.f90.o src/csv_module.F90.o src/csv_parameters.f90.o src/csv_utilities.f90.o ./gen-deps.awk src/tests/csv_read_test.f90 > src/tests/csv_read_test.f90.d gfortran -c -o src/tests/csv_read_test.f90.o src/tests/csv_read_test.f90 gfortran -o src/tests/csv_read_test.exe src/tests/csv_read_test.f90.o libcsv.a ./gen-deps.awk src/tests/csv_test.f90 > src/tests/csv_test.f90.d gfortran -c -o src/tests/csv_test.f90.o src/tests/csv_test.f90 gfortran -o src/tests/csv_test.exe src/tests/csv_test.f90.o libcsv.a ./gen-deps.awk src/tests/csv_write_test.f90 > src/tests/csv_write_test.f90.d gfortran -c -o src/tests/csv_write_test.f90.o src/tests/csv_write_test.f90 gfortran -o src/tests/csv_write_test.exe src/tests/csv_write_test.f90.o libcsv.a ``` -------------------------------- ### Do loop Source: https://fortran-lang.org/learn/quickstart/operators_control_flow This example demonstrates a basic 'do' loop construct in Fortran. It uses an integer counter variable 'i' to iterate from a start value to a final value. ```fortran integer :: i do i = 1, 10 print *, i end do ``` -------------------------------- ### Setting up a wtype object Source: https://fortran-lang.org/learn/oop_features_in_fortran/object_oriented_programming_techniques Example of how to set up a 'wtype' object using the 'setup_wtype' procedure, demonstrating polymorphic object initialization and rank-changing pointer assignment. ```Fortran use mod_wtype type(initialize) :: c_nz, c_w type(wtype) :: my_wtype integer :: i, j integer :: ndim ndim = ... associate ( my_data => [ ((real (max(0, min(i-j+2, j-i+2))), j=1, ndim), i=1, ndim) ] ) c_nz = initialize("nonzeros", count(my_data /= 0)) c_w = initialize("w", my_data, [ ndim, ndim ] ) end associate call setup_wtype(my_wtype, c_nz) call setup_wtype(my_wtype, c_w) ``` -------------------------------- ### Main Program Example Source: https://fortran-lang.org/learn/f95_features/program_units_and_procedures A simple 'Hello world!' main program. ```fortran program test print*,'Hello world!' end program test ``` -------------------------------- ### Using type(c_ptr) Pointer - Usage Source: https://fortran-lang.org/learn/best_practices/type_casting Example demonstrating the use of 'type(c_ptr)' to pass data to a callback function, using 'c_loc' to get the pointer and 'c_f_pointer' to cast it back. ```fortran module test use types, only: dp use integrals, only: simpson use iso_c_binding, only: c_ptr, c_loc, c_f_pointer implicit none private public foo type f_data ! Only contains data that we need for our particular callback. real(dp) :: a, k end type contains real(dp) function f(x, data) result(y) real(dp), intent(in) :: x type(c_ptr), intent(in) :: data type(f_data), pointer :: d call c_f_pointer(data, d) y = d%a * sin(d%k * x) end function subroutine foo(a, k) real(dp) :: a, k type(f_data), target :: data data%a = a data%k = k print *, simpson(f, 0._dp, pi, c_loc(data)) print *, simpson(f, 0._dp, 2*pi, c_loc(data)) end subroutine end module ``` -------------------------------- ### Install command-line tools (macOS) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs essential command-line developer tools, which include gfortran if Xcode is installed. ```bash xcode-select --install ``` -------------------------------- ### Install gfortran (Arch-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs the gcc-fortran package using pacman. ```bash sudo pacman -S gcc-fortran ``` -------------------------------- ### Creating a New File for Writing Source: https://fortran-lang.org/learn/best_practices/file_io Demonstrates how to open a file with `status='new'` and `action='write'` to create a new file or overwrite an existing one. ```Fortran integer :: io open(newunit=io, file="log.txt", status="new", action="write") write(io, *) a, b close(io) ``` -------------------------------- ### Install gfortran (RPM-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs the gcc-gfortran package using yum. ```bash sudo yum install gcc-gfortran ``` -------------------------------- ### Directory structure and source files Source: https://fortran-lang.org/learn/building_programs/project_make Check the directory structure and the source files of the Fortran CSV module. ```bash . ├── build.sh ├── files │   ├── test_2_columns.csv │   └── test.csv ├── fortran-csv-module.md ├── LICENSE ├── README.md └── src ├── csv_kinds.f90 ├── csv_module.F90 ├── csv_parameters.f90 ├── csv_utilities.f90 └── tests ├── csv_read_test.f90 ├── csv_test.f90 └── csv_write_test.f90 ``` -------------------------------- ### Install gcc (macOS with Homebrew) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs the GCC suite, which includes gfortran, using Homebrew. ```bash brew install gcc ``` -------------------------------- ### Creating a static library on Windows using 'lib' Source: https://fortran-lang.org/learn/building_programs/managing_libraries Steps to compile source files into object files and then create a static library using the 'lib' utility. ```cmd c:\...> ifort -c file1.f90 file2.f90 c:\...> ifort -c file3.f90 ... c:\...> lib /out:supportlib.lib file1.obj file2.obj c:\...> lib supportlib.lib file3.obj ... ``` -------------------------------- ### Install gfortran (Fedora 22+ / RHEL 8+) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs the gcc-gfortran package using dnf. ```bash sudo dnf install gcc-gfortran ``` -------------------------------- ### Meson setup command Source: https://fortran-lang.org/learn/building_programs/build_tools Command to configure the low-level build system using Meson. ```bash meson setup build ``` -------------------------------- ### Simple Fortran Program Source: https://fortran-lang.org/learn/building_programs A basic 'Hello, World!' program written in Fortran. ```fortran program hello write(*,*) 'Hello!' end program hello ``` -------------------------------- ### Example Makefile integration for dependency generation Source: https://fortran-lang.org/learn/building_programs/project_make This snippet shows how to integrate the dependency generation into a Makefile, disabling default rules and setting the project name. ```makefile # Disable the default rules MAKEFLAGS += --no-builtin-rules --no-builtin-variables # Project name NAME := csv ``` -------------------------------- ### Install specific gfortran version (Debian-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs a specific version of gfortran, e.g., version 8. ```bash sudo apt install gfortran-8 ``` -------------------------------- ### Install gcc version (macOS with MacPorts) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Installs a specific GCC version, e.g., gcc10, using MacPorts. ```bash sudo port install gcc10 ``` -------------------------------- ### Building a dynamic library on Windows with Intel Fortran Source: https://fortran-lang.org/learn/building_programs/managing_libraries Steps to compile source files and then link them into a dynamic link library (.dll). ```cmd $ ifort -c file1.f90 file2.f90 $ ifort -c file3.f90 ... $ ifort -dll -exe:supportlib.dll file1.obj file2.obj file3.obj ... ``` -------------------------------- ### Example command to run the awk script Source: https://fortran-lang.org/learn/building_programs/project_make This command makes the awk script executable and then runs it on all Fortran source files found in the 'src' directory. ```bash chmod +x gen-deps.awk ./gen-deps.awk $(find src -name '*.[fF]90') ``` -------------------------------- ### Basic File Opening and Closing Source: https://fortran-lang.org/learn/best_practices/file_io Demonstrates the fundamental workflow of opening a file to a unit identifier, performing operations, and then closing it. ```Fortran integer :: io open(newunit=io, file="log.txt") ! ... close(io) ``` -------------------------------- ### Add repository, update, and install newer gfortran (Debian-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Adds a PPA for newer toolchains, updates package lists, and installs gfortran version 10. ```bash sudo add-apt-repository ppa:ubuntu-toolchain-r/test sudo apt update sudo apt install gfortran-10 ``` -------------------------------- ### UBOUND Example Source: https://fortran-lang.org/learn/intrinsics/array A sample program demonstrating the usage of ubound, lbound, and size functions with different subroutines and interfaces. ```Fortran ! program demo_ubound module m2_bounds implicit none contains subroutine msub(arr) !!integer,intent(in) :: arr(*) ! cannot be assumed-size array integer,intent(in) :: arr(:) write(*,*)'MSUB: LOWER=',lbound(arr),'UPPER=',ubound(arr), & & 'SIZE=',size(arr) end subroutine msub end module m2_bounds ! program demo_ubound use m2_bounds, only : msub implicit none interface subroutine esub(arr) integer,intent(in) :: arr(:) end subroutine esub end interface integer :: arr(-10:10) write(*,*)'MAIN: LOWER=',lbound(arr),'UPPER=',ubound(arr), & & 'SIZE=',size(arr) call csub() call msub(arr) call esub(arr) contains subroutine csub write(*,*)'CSUB: LOWER=',lbound(arr),'UPPER=',ubound(arr), & & 'SIZE=',size(arr) end subroutine csub end subroutine esub(arr) implicit none integer,intent(in) :: arr(:) ! WARNING: IF CALLED WITHOUT AN EXPLICIT INTERFACE ! THIS WILL GIVE UNDEFINED ANSWERS (like 0,0,0) write(*,*)'ESUB: LOWER=',lbound(arr),'UPPER=',ubound(arr), & & 'SIZE=',size(arr) end subroutine esub !end program demo_ubound ``` -------------------------------- ### Check gfortran version (Debian-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran This command displays the installed gfortran version. ```bash gfortran --version ``` -------------------------------- ### Using Scratch Files Source: https://fortran-lang.org/learn/best_practices/file_io Explains the concept of scratch files, which are automatically deleted upon closing. ```Fortran open(status="scratch") ! ... close(io) ``` -------------------------------- ### Obscure merge example Source: https://fortran-lang.org/learn/intrinsics/array An obscure example of merge usage. ```Fortran merge(1.0/merge(x,1.0,x /= 0.0), 0.0, x /= 0.0) ``` -------------------------------- ### Creating a static library on Linux using 'ar' Source: https://fortran-lang.org/learn/building_programs/managing_libraries Steps to compile source files into object files and then create a static library using the 'ar' utility. ```bash $ gfortran -c file1.f90 file2.f90 $ gfortran -c file3.f90 ... $ ar r supportlib.a file1.o file2.o $ ar r supportlib.a file3.o ... ``` -------------------------------- ### License Tag Example Source: https://fortran-lang.org/learn/intrinsics Example of how to add a license tag to a Myst-Markdown file. ```markdown ###### fortran-lang intrinsic descriptions (License: MIT) @urbanjost ``` -------------------------------- ### Ninja build output Source: https://fortran-lang.org/learn/building_programs/build_tools Example output from the 'ninja -C build' command, showing the compilation and linking steps. ```text [1/4] Compiling Fortran object 'my_prog@exe/functions.f90.o'. [2/4] Dep hack [3/4] Compiling Fortran object 'my_prog@exe/tabulate.f90.o'. [4/4] Linking target my_prog. ``` -------------------------------- ### Elemental subroutine example Source: https://fortran-lang.org/learn/f95_features/array_handling Provides an example of an elemental subroutine. ```Fortran elemental subroutine swap(a, b) real, intent(inout) :: a, b real :: work work = a a = b b = work end subroutine swap ``` -------------------------------- ### Test gfortran (OpenBSD) Source: https://fortran-lang.org/learn/os_setup/install_gfortran Tests the installed Fortran compiler, which is named 'egfortran' on OpenBSD. ```bash egfortran -v ``` -------------------------------- ### Linking a static library Source: https://fortran-lang.org/learn/building_programs/managing_libraries Example of linking a program with a static library file (.a on Linux, .lib on Windows). ```bash $ gfortran -o tabulate tabulate.f90 functions.o supportlib.a ``` -------------------------------- ### Formatted Input/Output Examples Source: https://fortran-lang.org/learn/f95_features/data_transfer Illustrates various forms of I/O lists with simple formats for printing variables and expressions. ```Fortran integer :: i real, dimension(10) :: a character(len=20) :: word print "(i10)", i print "(10f10.3)", a print "(3f10.3)", a(1), a(2), a(3) print "(a10)", word(5:14) print "(3f10.3)", a(1) * a(2) + i, sqrt(a(3:4)) ``` -------------------------------- ### CMake configuration output (initial) Source: https://fortran-lang.org/learn/building_programs/build_tools Example output when configuring a CMake project, showing the detected Fortran compiler. ```text -- The Fortran compiler identification is GNU 10.2.0 -- Detecting Fortran compiler ABI info -- Detecting Fortran compiler ABI info - done -- Check for working Fortran compiler: /usr/bin/f95 - skipped -- Checking whether /usr/bin/f95 supports Fortran 90 -- Checking whether /usr/bin/f95 supports Fortran 90 - yes -- Configuring done -- Generating done -- Build files have been written to: /home/awvwgk/Examples/build ``` -------------------------------- ### Close statement example Source: https://fortran-lang.org/learn/f95_features/operations_on_external_files An example of the close statement. ```Fortran close (unit=2, iostat=ios, status="delete") ``` -------------------------------- ### Examples Source: https://fortran-lang.org/learn/intrinsics/array Sample program demonstrating the PRODUCT intrinsic function with various scenarios, including factorial calculations, masked products, zero-sized arrays, and multi-dimensional arrays. ```Fortran program demo_product implicit none character(len=*),parameter :: all='(*(g0,1x))' ! a handy format character(len=1),parameter :: nl=new_line('a') NO_DIM: block ! If DIM is not specified, the result is the product of all the ! selected array elements. integer :: i,n, p1, p2 integer,allocatable :: array(:) ! all elements are selected by default do n=1,10 print all, 'factorial of ',n,' is ', product([(real(i),i=1,n)]) enddo ! using a mask array=[10,12,13,15,20,25,30] p1=product(array, mask=mod(array, 2)==1) ! only odd elements p2=product(array, mask=mod(array, 2)/=1) ! only even elements print all, nl,'product of all elements',product(array) ! all elements print all, ' odd * even =',nl,p1,'*',p2,'=',p1*p2 ! NOTE: If ARRAY is a zero-sized array, the result is equal to one print all print all, 'zero-sized array=>',product([integer :: ]) ! NOTE: If nothing in the mask is true, this also results in a null ! array print all, 'all elements have a false mask=>', & & product(array,mask=.false.) endblock NO_DIM WITH_DIM: block integer :: rect(2,3) integer :: box(2,3,4) ! lets fill a few arrays rect = reshape([ & 1, 2, 3, & 4, 5, 6 & ],shape(rect),order=[2,1]) call print_matrix_int('rect',rect) ! Find the product of each column in RECT. print all, 'product of columns=',product(rect, dim = 1) ! Find the product of each row in RECT. print all, 'product of rows=',product(rect, dim = 2) ! now lets try a box box(:,:,1)=rect box(:,:,2)=rect*(+10) box(:,:,3)=rect*(-10) box(:,:,4)=rect*2 ! lets look at the values call print_matrix_int('box 1',box(:,:,1)) call print_matrix_int('box 2',box(:,:,2)) call print_matrix_int('box 3',box(:,:,3)) call print_matrix_int('box 4',box(:,:,4)) ! remember without dim= even a box produces a scalar print all, 'no dim gives a scalar',product(real(box)) ! only one plane has negative values, so note all the "1" values ! for vectors with no elements call print_matrix_int('negative values', & & product(box,mask=box < 0,dim=1)) ! If DIM is specified and ARRAY has rank greater than one, the ! result is a new array in which dimension DIM has been eliminated. ! pick a dimension to multiply though call print_matrix_int('dim=1',product(box,dim=1)) call print_matrix_int('dim=2',product(box,dim=2)) call print_matrix_int('dim=3',product(box,dim=3)) endblock WITH_DIM contains subroutine print_matrix_int(title,arr) implicit none !@(#) print small 2d integer arrays in row-column format character(len=*),intent(in) :: title integer,intent(in) :: arr(:,:) integer :: i character(len=:),allocatable :: biggest print all print all, trim(title),':(',shape(arr),')' ! print title biggest=' ' ! make buffer to write integer into ! find how many characters to use for integers write(biggest,'(i0)')ceiling(log10(real(maxval(abs(arr)))))+2 ! use this format to write a row biggest='("> [",*(i'//trim(biggest)//":,"))' ! print one row of array at a time do i=1,size(arr,dim=1) write(*,fmt=biggest,advance='no')arr(i,:) write(*,'( " ]")') enddo end subroutine print_matrix_int end program demo_product ``` -------------------------------- ### Check if gfortran is installed (Debian-based) Source: https://fortran-lang.org/learn/os_setup/install_gfortran This command checks if the gfortran executable is available in the system's PATH. ```bash which gfortran ``` -------------------------------- ### Building the executable program on GNU/Linux Source: https://fortran-lang.org/learn/building_programs/managing_libraries Command to link the main program with the dynamic library to create an executable. ```bash $ gfortran -o tabulate tabulate.f90 functions.dll ``` -------------------------------- ### Make output with trailing whitespace Source: https://fortran-lang.org/learn/building_programs/build_tools Shows the output of the previous Make example, highlighting the preserved trailing whitespace. ```text echo "/usr /lib" /usr /lib ``` -------------------------------- ### index Example Source: https://fortran-lang.org/learn/intrinsics/character Example program demonstrating the usage of the index intrinsic function with different options. ```Fortran program demo_index implicit none character(len=*),parameter :: str=& 'Search this string for this expression' !1234567890123456789012345678901234567890 write(*,*)& index(str,'this').eq.8, & ! return value is counted from the left end even if BACK=.TRUE. index(str,'this',back=.true.).eq.24, & ! INDEX is case-sensitive index(str,'This').eq.0 end program demo_index ``` -------------------------------- ### Internal File Write Example Source: https://fortran-lang.org/learn/f95_features/data_transfer Example of writing formatted data into a character variable (internal file). ```Fortran integer :: day real :: cash character(len=50) :: line : ! write into line write (unit=line, fmt="(a, i2, a, f8.2, a)") "Takings for day ", day, & " are ", cash, " dollars" ``` -------------------------------- ### Inquire statement example output Source: https://fortran-lang.org/learn/f95_features/operations_on_external_files The output from the inquire statement example. ```text ex .true. op .true. nam cities acc direct seq no frm unformatted irec 100 nr 1 ``` -------------------------------- ### Building with SCons (quiet output) Source: https://fortran-lang.org/learn/building_programs/build_tools Building the project with SCons using the -Q flag for less verbose output. ```bash scons -Q ``` -------------------------------- ### Open statement example Source: https://fortran-lang.org/learn/f95_features/operations_on_external_files An example of the open statement with various specifiers. ```Fortran open (unit=2, iostat=ios, file="cities", status="new", access="direct", & action="readwrite", recl=100) ``` -------------------------------- ### Compiler error example Source: https://fortran-lang.org/learn/building_programs/compiling_source This example shows compiler output when there is a syntax error in the source code. ```bash $ gfortran hello3.f90 hello.f90:1:0: 1 | prgoram hello | Error: Unclassifiable statement at (1) hello3.f90:3:17: 3 | end program hello | 1 Error: Syntax error in END PROGRAM statement at (1) f951: Error: Unexpected end of file in 'hello.f90' ``` -------------------------------- ### Building a dynamic library on GNU/Linux Source: https://fortran-lang.org/learn/building_programs/managing_libraries Command to compile a Fortran source file into a shared dynamic library using gfortran. ```bash $ gfortran -shared -o functions.dll functions.f90 ``` -------------------------------- ### set_exponent example Source: https://fortran-lang.org/learn/intrinsics/model Sample program demonstrating the use of set_exponent and fraction intrinsics. ```Fortran program demo_setexp implicit none real :: x = 178.1387e-4 integer :: i = 17 print *, set_exponent(x, i), fraction(x) * radix(x)**i end program demo_setexp ``` -------------------------------- ### Elemental Function Example Source: https://fortran-lang.org/learn/best_practices/element_operations An example of an elemental function `nroot` that calculates the nth root of a number. ```fortran real(dp) elemental function nroot(n, x) result(y) integer, intent(in) :: n real(dp), intent(in) :: x y = x**(1._dp / n) end function ``` -------------------------------- ### Interface for Setting Container Components Source: https://fortran-lang.org/learn/oop_features_in_fortran/object_oriented_programming_techniques Illustrates an overloaded structure constructor and a subroutine 'setup_wtype' to manage components of a 'wtype' structure using a generic 'any_object'. ```Fortran module mod_wtype use mod_utility_types, only : initialize => any_object type :: wtype private integer :: nonzeros = -1 real, allocatable :: w(:,:) end type wtype contains subroutine setup_wtype(a_wtype, a_component) ! in-place setting to avoid memory bursts for large objects type(wtype), intent(inout) :: a_wtype type(initialize), intent(in), target :: a_component integer :: wsize real, pointer :: pw(:,:) select case (a_component%description) case ("nonzeros") if ( allocated(a_component%value) ) then select type ( nonzeros => a_component%value(1) ) type is (integer) a_wtype%nonzeros = nonzeros end select end if case ("w") if ( allocated(a_component%value) .and. allocated(a_component%shape) ) then wsize = size(a_component%value) if ( wsize >= product(a_component%shape) ) then select type ( w => a_component%value ) type is (real) pw(1:a_component%shape(1), 1:a_component%shape(2)) => w a_wtype%w = pw end select end if end if end select end subroutine setup_wtype : end module ```