Arrays
Arrays
Built and Summed
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
nums ← [1, 2, 3, 4]
4integer :: total5nums = [1, 2, 3, 4]6total = sum(nums)values this step[1, 2, 3, 4]numstotal ← 10
5nums = [1, 2, 3, 4]6total = sum(nums)7print '(I0)', totalvalues this step10total[1, 2, 3, 4]numsprint '(I0)', total
6 total = sum(nums)7 print '(I0)', total8end program arraysoutput10values this step10total
Build, Then Sum
nums(4)reserves four integer slots.[1, 2, 3, 4]fills those slots in order.sum(nums)adds every element.- 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