An array constructor [a, b, c] initializes a fixed-shape array. sum adds all elements at once.

Program

Play the program to build a 4-element array and sum it.

arrays.f90
Replay: real traced execution (multi-file project)
program arrays
    implicit none
    integer :: nums(4)
    integer :: total
    nums = [1, 2, 3, 4]
    total = sum(nums)
    print '(I0)', total
end program arrays
  1. nums ← [1, 2, 3, 4]

    4integer :: total5nums = [1, 2, 3, 4]6total = sum(nums)
    values this step[1, 2, 3, 4]nums
  2. total ← 10

    5nums = [1, 2, 3, 4]6total = sum(nums)7print '(I0)', total
    values this step10total[1, 2, 3, 4]nums
  3. print '(I0)', total

    6    total = sum(nums)7    print '(I0)', total8end program arrays
    output10
    values this step10total

Build, Then Sum

  1. nums(4) reserves four integer slots.
  2. [1, 2, 3, 4] fills those slots in order.
  3. sum(nums) adds every element.
  4. The printed total is 10. | Position | Value | | --- | --- | | 1 | 1 | | 2 | 2 | | 3 | 3 | | 4 | 4 |
array constructor `[1, 2, 3, 4]` builds a rank-1 array.
sum `sum(nums)` reduces an array to one scalar.
one-based index Fortran arrays start at index 1 by default.

Exercise: arrays.f90

Build a four-value integer array, sum it, and print the total