Fortran Lab Examples

Twenty-two runnable single-file programs that follow the track's lesson order, grouped by category. Every file is self-contained and fully commented. Run them locally with the compiler listed on the page, or open them in the code viewer — then change one thing and run again. That second run is where the learning happens.

Foundations

Hello world, the five intrinsic types with KIND, operator precedence, and the declaration discipline. These four files introduce every value and habit the later demos rely on.

#DescriptionLink
1Hello, name — program unit, implicit none, trimmed outputView
2Intrinsic types and the KIND parameterView
3Operator precedence and the integer-division trapsView
4Declaration syntax and named constantsView

Control Flow

Decisions (IF ladder and SELECT CASE), the three loop families, and the parallel-ready do concurrent reduction with Fortran 2018 locality.

#DescriptionLink
5IF ladder and SELECT CASE decision patternsView
6Counted DO, named EXIT scan, DO WHILE convergenceView
7DO CONCURRENT with REDUCE — race-free summationView

Programming

Functions and subroutines with INTENT, elemental procedures, array slicing and WHERE masks, deferred-length strings with internal files, derived types, and the module + USE pattern.

#DescriptionLink
8Function vs subroutine, INTENT contractsView
9Elemental function: one body, array and scalar callsView
10Array constructors, slicing, strides, WHEREView
11Deferred-length strings and internal filesView
12Derived types: definition, constructor, value copyView
13Module with private API and USE ONLY importsView

Files & I/O

Formatted output, robust record-based reading with iostat/iomsg, and NAMELIST configuration files that write and read themselves.

#DescriptionLink
14FORMAT descriptors and robust file readingView
15NAMELIST: config files without a parserView

Parallel & HPC

The three big parallel models, each in one compilable file. OpenMP needs -fopenmp; coarrays run single-image out of the box; the MPI ring needs OpenMPI/MPICH.

#DescriptionLink
16OpenMP fork-join with REDUCTION — pi integrationView
17Coarrays: images and the CO_SUM collectiveView
18MPI ring: point-to-point send/recv around a circleView

Interoperability

Crossing the language boundary in both directions: a bind(c) library with its C caller, and the F2PY bridge whose Python driver calls the Fortran kernel every time step.

#DescriptionLink
19iso_c_binding library export (Fortran)View
20C caller of the same library (C)View
21F2PY kernel — one Euler step (Fortran)View
22F2PY driver — Python orchestrationView
How to run them. Compile straight from the demo folder: gfortran -Wall -o demo demo/foundations/01_hello.f90. Demos 5–15 need only gfortran; 16 needs -fopenmp; 17 works with plain gfortran (single image) or -fcoarray=lib; 18 needs mpifort + mpiexec -n 4; the interop pair compile with the commands in their own comments. Larger multi-file study projects follow in Study Projects.