Array sections

a(2:5) slices

The colon picks a contiguous range: a(2:5) starts at index 2 and stops at index 5, giving four elements.

Both bounds stay inside the array, and the result keeps the original order, so printing it shows 2 3 4 5.

program slices implicit none integer :: a(10) integer :: i a = [(i, i = 1, 10)] print *, a(2:5) end program slices

./slices

2 3 4 5

Strides

A second colon adds a stride: a(1:10:2) takes every second element, while a negative stride walks backward through the array.

Strides keep code short: one slice replaces a whole loop for sampling, reversing, or skipping elements.

program strides implicit none integer :: a(10) integer :: i a = [(i, i = 1, 10)] print *, a(1:10:2) print *, a(10:1:-2) end program strides

./strides

1 3 5 7 9
10 8 6 4 2

Whole-array assignment

Whole arrays can be assigned in one statement with no loop: every element gets the same operation at once.

Both sides must agree in shape, and then b = a * 10 fills b with 10 20 30 40 50 in a single line.

program whole implicit none integer :: a(5) integer :: b(5) a = [1, 2, 3, 4, 5] b = a * 10 print *, b end program whole

./whole

10 20 30 40 50

WHERE masks

WHERE applies an assignment only where a mask is true, leaving all other elements untouched.

Here b starts at zero and only takes values from a where a is greater than 5, giving 0 7 0 9 0.

program masks implicit none integer :: a(5) integer :: b(5) a = [3, 7, 1, 9, 4] b = 0 where (a > 5) b = a end where print *, b end program masks

./masks

0 7 0 9 0

The code on this page was run with gfortran 15.2.0 on Alpine Linux 3.24 (x86_64) in a Docker container.

Article author: Arthur Isaev