Hello World (first programs) · Beginner · 15 min
Hello World in Fortran: gfortran and implicit none
By Padding · Updated 18 Nov 2026
gfortran 16.2 (GCC 16.2) · gcc:16 image (Debian 13) · Ubuntu 26.04 ships gfortran 15.2
You will compile and run a free-form Fortran program with gfortran, see why every program should start with implicit none, and read a number to print a formatted table of squares from a 1-based array.
On this page
Fortran is the oldest programming language still in everyday use, and it has kept up. The name comes from "formula translation": it was built in the 1950s so scientists could write maths the way they wrote it on paper and get fast machine code back. Modern Fortran is a different language from the punched-card version. The current standards, Fortran 2018 and Fortran 2023, have free-form source, modules, dynamic arrays, whole-array arithmetic and built-in parallel features.
Fortran is compiled ahead of time, like C. You write a .f90 file, a compiler turns it into a native program, and you run that program. The free compiler on Linux is gfortran, the Fortran front end of GCC, the GNU Compiler Collection. The gfortran command compiles your source and links it with the Fortran runtime library, libgfortran, which does the printing, reading and error reporting your program asks for.
You will meet the two habits that save Fortran beginners the most time: putting implicit none at the top of every program, and knowing why print * puts a space in front of your text. Then you go one step further: read a number, fill a 1-based array with a do loop, square it in a single statement and print a lined-up table with a format.
Fortran runs the weather and climate models that national weather services use (the widely used WRF model is written in it), large parts of physics and engineering simulation, and much of the work on supercomputers. The reference version of LAPACK, the linear algebra library under NumPy, R and MATLAB, is Fortran.
You work in a throwaway folder, ~/hello-fortran-demo, and delete it at the end.
Step 1 · Install gfortran
On Ubuntu 26.04, install the gfortran package:
sudo apt update
sudo apt install -y gfortranThen check the version:
gfortran --versionUbuntu 26.04 installs gfortran 15.2. The newest release is GCC 16.2, from August 2026, and everything in this tutorial works the same on either. The download happens once; after that, compiling needs no internet connection, which helps if you work on prepaid data.
On Windows, the simplest route is WSL: install Ubuntu from the Microsoft Store and follow the Ubuntu commands. For native Windows programs, install MSYS2 (msys2.org) and in its UCRT64 terminal run pacman -S mingw-w64-ucrt-x86_64-gcc-fortran. On macOS, brew install gcc installs GCC 16, and its Fortran compiler answers to gfortran.
Check it worked
The first line names the compiler and version, for example GNU Fortran (Ubuntu 15.2.0-...) 15.2.0 on Ubuntu or GNU Fortran (GCC) 16.2.0 with GCC 16. If you see gfortran: command not found, the install did not finish; run the apt install line again and read its last lines for an error.
Step 2 · Write hello.f90
Make the demo folder and create the source file:
mkdir -p ~/hello-fortran-demo
cd ~/hello-fortran-demo
cat > hello.f90 <<'F90'
program hello
! Print a greeting and stop.
implicit none
print *, 'Hello, world!'
end program hello
F90You can type the same five lines into a text editor and save them as hello.f90 instead. Line by line:
program hellostarts the main program and names ithello. The name is a label for you and the compiler; it does not have to match the file name.! Print a greeting and stop.is a comment. Everything after!on a line is ignored.implicit nonetells the compiler that every variable must be declared before use. The next step shows why this matters. It must come before any declarations or statements.print *, 'Hello, world!'writes the text to the screen. The*means "list-directed": let the compiler choose the layout. Strings can use single or double quotes.end program helloends the program. Repeating the name is optional, but if you write it, it must match the name on the first line.
Fortran is not case-sensitive, so PRINT, Print and print are the same keyword. Older code is often in capitals; modern code is usually lower case.
The .f90 extension tells gfortran the file is free-form source: you can start statements in any column, indent as you like and write lines up to 132 characters. The older fixed-form layout, used in files ending .f or .for, reserves columns 1 to 6 for labels and markers and puts statements in columns 7 to 72. The 90 refers to Fortran 90, which introduced free form; use .f90 for new code whatever standard you write to.
Check it worked
cat hello.f90 prints the five lines exactly as above, starting with program hello.
Step 3 · Compile and run it
Compile the file into a program called hello, then run it:
cd ~/hello-fortran-demo
gfortran -Wall -o hello hello.f90
./hello
echo "exit code: $?"-Wallturns on gfortran's common warnings, including unused variables and suspicious arithmetic. Use it on every build.-o hellonames the output file. Without it gfortran writesa.out../helloruns the program from the current folder. The shell does not look in the current folder for commands, so the./is needed.$?holds the exit code of the last command. Reachingend programexits with 0, which means success.
The output is Hello, world! with a space in front. That is not a mistake in your code. List-directed output lets the compiler choose the layout, and gfortran starts every line with a blank. The habit dates from line printers, which used the first character of each line to control the paper feed, so a blank meant "normal line".
To control the layout yourself, give print a format instead of *. Add a second program that prints the text exactly, then a number both ways:
cd ~/hello-fortran-demo
cat > exact.f90 <<'F90'
program exact
implicit none
print '(a)', 'Hello, world!'
print *, 'Two plus two is', 2 + 2
print '(a, i0)', 'Two plus two is ', 2 + 2
end program exact
F90
gfortran -Wall -o exact exact.f90
./exact'(a)' is a format string. The a edit descriptor prints a character value as it is. In '(a, i0)', i0 prints an integer in as few columns as it needs. List-directed output pads numbers to a fixed width, which is why the second line has a wide gap before the 4.
Check it worked
./hello prints Hello, world! with a leading space and the next line reads exit code: 0. ./exact prints three lines: Hello, world! with no space, Two plus two is followed by several spaces and 4, and Two plus two is 4.
Step 4 · See what implicit none protects you from
Without implicit none, Fortran invents a variable for any name it has not seen. Names starting with i to n become integers and everything else becomes real (floating-point) numbers. That rule made sense in the 1950s, but it means a typo quietly becomes a new variable. Write a program with a typo in it, with implicit none in place:
cd ~/hello-fortran-demo
cat > typo.f90 <<'F90'
program typo
implicit none
integer :: total
total = 3
print *, 'Total:', totl
end program typo
F90
gfortran -Wall -o typo typo.f90 || echo "compile failed"integer :: totaldeclares a whole-number variable calledtotal. The::separates the type from the names.total = 3assigns a value.totlis the typo.
gfortran stops with an error like Symbol 'totl' at (1) has no IMPLICIT type, and prints the line with a marker under the (1) position. No program is produced, so you fix the name and move on.
Delete the implicit none line and the same file compiles. It prints whatever was in the memory for an undefined real variable called totl, often 0.00000000, with no error. In a 10,000-line climate model, that kind of bug can survive for years. Put implicit none in every program and module you write. gfortran also has a flag, -fimplicit-none, that applies it to a whole file, but writing it in the code keeps the code safe whichever compiler builds it.
Check it worked
The compile prints an error containing has no IMPLICIT type and then compile failed, and ls typo reports that no file called typo exists.
Step 5 · Read a number and print a table of squares
Now a program that asks how many squares to print, stores the numbers in an array and prints a lined-up table. Create squares.f90:
cd ~/hello-fortran-demo
cat > squares.f90 <<'F90'
program squares
implicit none
integer :: n, i, ios
integer, allocatable :: nums(:), sq(:)
print '(a)', 'How many squares (1 to 20)?'
read (*, *, iostat=ios) n
if (ios /= 0) error stop 'Please enter a whole number.'
if (n < 1 .or. n > 20) error stop 'Please enter a number from 1 to 20.'
allocate (nums(n))
do i = 1, n
nums(i) = i
end do
sq = nums**2
write (*, '(a4, a8)') 'n', 'n**2'
do i = 1, n
write (*, '(i4, i8)') nums(i), sq(i)
end do
print '(a, i0)', 'Sum of squares: ', sum(sq)
print '(a, i0, a, i0)', 'First element sq(1) = ', sq(1), ', last element = ', sq(n)
end program squares
F90
gfortran -Wall -std=f2018 -o squares squares.f90What each part does:
integer :: n, i, iosdeclares three integers: the count, a loop counter and a status code for the read.integer, allocatable :: nums(:), sq(:)declares two one-dimensional integer arrays whose size is decided while the program runs.(:)means "one dimension, size not known yet".read (*, *, iostat=ios) nreads a number from the keyboard. The first*is the keyboard (standard input), the second is list-directed format.iostat=iosputs 0 iniosif the read worked and a non-zero code if it did not, instead of crashing.error stop '...'ends the program with a message and a non-zero exit code..or.is Fortran's "or";/=means "not equal".allocate (nums(n))creates the array withnelements, numbered 1 ton. Fortran arrays start at 1 unless you say otherwise.do i = 1, n...end dois a counted loop:itakes the values 1, 2 and so on up ton, includingn. Inside it,nums(i) = ifills elementi. Fortran uses round brackets for array elements.sq = nums**2squares every element ofnumsin one statement.**is the power operator. This is a whole-array operation: no loop, and becausesqis allocatable, Fortran sizes it to match on assignment. Compilers turn statements like this into fast vector code.write (*, '(a4, a8)') 'n', 'n**2'writes the headings.a4prints text right-aligned in 4 columns,a8in 8.write (*, '(i4, i8)') nums(i), sq(i)prints one row: an integer in 4 columns, then one in 8, so the columns line up under the headings.print 'fmt'andwrite (*, 'fmt')do the same job here;writecan also send output to files.sum(sq)is a built-in (intrinsic) function that adds every element. Others includemaxval,minvalandsize.-std=f2018makes gfortran check the code against the Fortran 2018 standard and reject GNU-only extensions. gfortran 15 and 16 also accept-std=f2023.
Run it and type a number when asked:
./squaresYou can also give it the answer through a pipe:
cd ~/hello-fortran-demo
echo 5 | ./squaresCheck it worked
With 5 as input, the output is:
How many squares (1 to 20)?
n n**2
1 1
2 4
3 9
4 16
5 25
Sum of squares: 55
First element sq(1) = 1, last element = 25The numbers sit right-aligned under their headings. Compiling printed nothing, which means -Wall and -std=f2018 found nothing to report.
Step 6 · Handle bad input and out-of-range indexes
Try the two inputs the program refuses:
cd ~/hello-fortran-demo
echo abc | ./squares || echo "exit code: $?"
echo 50 | ./squares || echo "exit code: $?"Each run prints ERROR STOP followed by the message, then a non-zero exit code. Without iostat=ios, the abc run would stop with a runtime error from libgfortran instead of your own message.
Because arrays start at 1, a loop written do i = 0, n, a habit from C, Python or JavaScript, reads an element that does not exist. By default Fortran does not check, for speed, so the program may print rubbish or crash. Turn on bounds checking with -fcheck=bounds while you learn and test:
cd ~/hello-fortran-demo
cat > bounds.f90 <<'F90'
program bounds
implicit none
integer :: a(3), i
a = [10, 20, 30]
i = 0
print *, a(i)
end program bounds
F90
gfortran -Wall -fcheck=bounds -o bounds bounds.f90
./bounds || echo "exit code: $?"integer :: a(3) is a fixed-size array of three elements, a(1) to a(3), and [10, 20, 30] is an array constructor that fills all three at once. With -fcheck=bounds the program stops with a message like Fortran runtime error: Index '0' of dimension 1 of array 'a' below lower bound of 1. If you want an array that starts at 0, declare it that way: integer :: b(0:2) has elements b(0), b(1) and b(2).
Check it worked
The abc run prints ERROR STOP Please enter a whole number., the 50 run prints ERROR STOP Please enter a number from 1 to 20., and both print a non-zero exit code. The bounds program prints a runtime error mentioning below lower bound of 1 instead of a number.
Step 7 · Recognise the other mistakes beginners make
Integer division. In Fortran, as in C, dividing two integers gives an integer and drops the fraction:
cd ~/hello-fortran-demo
cat > divide.f90 <<'F90'
program divide
implicit none
print *, 7 / 2
print *, 7.0 / 2.0
end program divide
F90
gfortran -Wall -o divide divide.f90
./divideThe first line prints 3, the second 3.50000000. With -Wall, gfortran also warns at compile time that the integer division truncates its result. Write at least one number with a decimal point when you want a fraction.
Saving free-form code as .f. gfortran reads a .f file as fixed form, so modern code saved with that extension fails with errors about the first columns:
cd ~/hello-fortran-demo
cp hello.f90 hello.f
gfortran -o hello-fixed hello.f || echo "compile failed"You see errors such as Non-numeric character in statement label, because in fixed form columns 1 to 5 are kept for numeric labels. Rename the file to .f90.
Unexpected spaces in output. If your text appears with a leading space or numbers have wide gaps, that is print *. Use a format such as '(a)' or '(a, i0)' when the layout matters.
Check it worked
./divide prints 3 on its first line and 3.50000000 on its second. The .f compile prints errors and compile failed.
Step 8 · Clean up and know where to go for projects
Delete the demo folder:
cd ~
rm -rf ~/hello-fortran-demoFor anything bigger than one file, use the Fortran Package Manager, fpm (fpm.fortran-lang.org). It creates a project layout with folders for your program, modules and tests, fetches dependencies and runs gfortran with the right flags for you, so fpm run replaces the compile commands you typed here.
Leave gfortran installed if you plan to carry on. To remove it, run sudo apt remove gfortran.
Check it worked
ls ~/hello-fortran-demo reports No such file or directory.
Next steps
- See a newer language built for the same scientific work, with a REPL instead of a compile step: Hello World in Julia.
- Compare Fortran's build with C's preprocess, compile and link stages: Hello World in C.
- Meet the other language from the 1950s still running in production, this time in banks: Hello World in COBOL.
Related tutorials
- Hello World in Zig: zig run, zig build and zig ccYou will install a signature-checked Zig 0.17.1 on Ubuntu 26.04, write and run Hello World with the current I/O API, build a small project with zig build that handles errors explicitly, and use zig cc to compile a C program for Linux and for Windows.
- Hello World in x86-64 assembly with NASM and Linux system callsYou will write an x86-64 assembly program that prints a line using only Linux system calls, assemble it with NASM, link it with ld, check its exit status, then loop it three times and read its machine code with objdump.
- Hello World in WebAssembly text format with wabt and WasmtimeYou will write a WebAssembly module by hand in the text format, assemble it with wat2wasm, print Hello World through WASI in Wasmtime 50, and call an exported add function from both Wasmtime and Node.js.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials