МатематикаМоя статистика
Тест по Fortran
120 вопросов в 10 темах (лёгкий — 42, средний — 50, сложный — 28). Выберите темы, уровень и количество вопросов — к каждому ответу есть объяснение.
Структура программы, типы и kind, массивы и column-major, циклы, процедуры и intent, модули, ввод-вывод и форматы, встроенные функции, точность вычислений, do concurrent и OpenMP. Вопросы на английском.
Все вопросы теста 120
Нажмите на вариант ответа, чтобы проверить себя, или «Показать ответ».
Program structure10
What does the statement implicit none do?
program demo
implicit none
integer :: n
n = 5
end program demo- It switches off implicit typing, so every variable must be declared explicitly
- It makes every undeclared variable default to REAL
- It forbids automatic conversion between INTEGER and REAL in expressions
- It initializes all declared variables to zero
Without implicit none, an undeclared name starting with I–N is INTEGER and any other name is REAL, so a typo silently creates a new variable. implicit none turns that into a compile-time error. It has nothing to do with initialization (variables start undefined) or with mixed-mode conversion, which still happens.
Which character starts a comment in free-form (.f90) Fortran source?
- C in column 1
- !
- //
- #
In free form, everything after ! (outside a character string) is a comment, and ! can appear anywhere on the line. A C or * in column 1 marks a comment only in FORTRAN 77 fixed form; // is the string concatenation operator, and # lines are preprocessor directives, not comments.
The program below has no implicit none and no declarations. What does it print?
program p
k = 7
x = k / 2
index2 = 2.9
print *, x, index2
end program p- 3.5 and 2.9
- 3.0 and 2
- 3.5 and 2
- 3.0 and 2.9
Implicit typing makes k and index2 INTEGER (names starting with I–N) and x REAL. k / 2 is integer division, giving 3, which is then converted to 3.0. Assigning 2.9 to the integer index2 truncates it to 2. Expecting 3.5 or 2.9 is exactly the bug implicit none is meant to prevent.
In FORTRAN 77 fixed-form source, which columns hold the statement text itself?
- Columns 1 to 80
- Columns 6 to 80
- Columns 1 to 72
- Columns 7 to 72
Fixed form reserves columns 1–5 for statement labels (C or * in column 1 for comments), column 6 for the continuation mark, and columns 7–72 for the statement. Anything after column 72 is ignored — a leftover of 80-column punched cards whose last 8 columns held sequence numbers.
This fixed-form FORTRAN 77 program has a period instead of a comma in the DO statement. What does it do?
PROGRAM P
DO 10 I = 1.10
PRINT *, 'BODY'
10 CONTINUE
PRINT *, DO10I
END- It fails to compile with a syntax error in the DO statement
- It runs the loop 10 times, treating 1.10 as the range 1 to 10
- It assigns 1.1 to an implicitly declared REAL variable DO10I, and the body runs once
- It runs the loop once with I = 1 and then stops
Blanks are insignificant in fixed form, so the line reads DO10I=1.10 — an assignment to a new REAL variable named DO10I. There is no loop at all: PRINT runs once and label 10 is just a CONTINUE. This is the classic reason free form (where blanks matter) and implicit none were introduced; the compiler cannot flag it as a syntax error.
By gfortran's file-name convention, which extension makes a source file be treated as fixed form?
- .f90
- .f03
- .f08
- .f
gfortran treats .f and .for (and .F, .FOR for preprocessed files) as FORTRAN 77-style fixed form, while .f90, .f95, .f03 and .f08 are free form. The number in .f90 only signals free form, not a language standard: a .f90 file can use Fortran 2018 features.
In one program unit, the names Total, TOTAL and total are used. How does Fortran treat them?
- As three different variables
- As a compile error, because names must be written consistently
- As the same variable only if implicit none is absent
- As the same variable, because Fortran is case-insensitive
Fortran keywords and names are case-insensitive (only the contents of character strings keep their case). Total, TOTAL and total all refer to one entity, and implicit none does not change that. Programmers from C or Python sometimes rely on case to tell variables apart, which silently merges them in Fortran.
How do you continue a long statement onto the next line in free-form source?
- Put any character in column 6 of the next line
- End the line with a backslash (\)
- End the line with an ampersand (&)
- Start the next line with a plus sign
In free form a trailing & means the statement continues on the next line (an optional & at the start of the next line marks where it resumes). The column-6 mark is the FORTRAN 77 fixed-form rule, and a backslash has no continuation meaning in Fortran.
Where must type declarations such as real :: x appear in a program unit?
- Anywhere, as long as they come before the variable's first use
- Only at the top of a module
- After the contains statement
- In the specification part, before the first executable statement (a BLOCK construct can start a new one)
A program unit has a specification part (implicit none, use, declarations) followed by an execution part; once an executable statement appears, no more declarations are allowed. Declaring variables mid-code as in C99 or C++ is a compile error. Fortran 2008 added block … end block for local declarations inside the executable code.
In this fixed-form (.f) file, the text '+ 100.0' occupies columns 73–80 of the long line. What is printed?
PROGRAM P
TOTAL = 1.0 + 2.0 + 3.0 + 4.0 + 5.0 + 6.0 + 7.0 + 8.0 + 9.0 + 10.0 + 100.0
PRINT *, TOTAL
END- 155.0
- Nothing: the line is too long and compilation fails
- 100.0
- 55.0
Fixed-form statements end at column 72; characters beyond it are silently ignored (gfortran only warns with -Wall: 'Line truncated'). The statement the compiler sees stops after + 10.0, so TOTAL is 55. This invisible truncation was a notorious source of wrong results in legacy code.
Types and kinds13
What does this statement print?
print *, 7/2, 7.0/2- 3.5 and 3.5
- 3 and 3.5
- 3 and 3
- 4 and 3.5
When both operands are INTEGER, / is integer division and truncates toward zero, so 7/2 is 3. If one operand is REAL (7.0), the other is converted and the result is 3.5. Rounding to 4 never happens with integer division.
On common compilers (gfortran, ifx), roughly how many significant decimal digits does a default REAL hold?
- About 15–16
- About 6–7
- About 33
- Exactly 10
Default REAL is almost always IEEE single precision (32 bits, 24-bit mantissa), which gives about 6–7 significant digits; precision(1.0) returns 6. The 15–16 digits people expect belong to double precision (real64), and 33 digits to quad precision.
x is double precision. What does the first print show (gfortran)?
integer, parameter :: dp = kind(1.0d0)
real(dp) :: x, y
x = 0.1
y = 0.1_dp
print *, x
print *, y- 0.10000000149011612
- 0.10000000000000001
- 0.1000000
- 0.10000000000000000
The literal 0.1 has default (single) kind, so it is first rounded to the nearest single-precision value and only then widened to double — the error of the single value (…149011612) becomes visible. 0.1_dp is rounded directly in double precision and prints 0.10000000000000001. Declaring x as real(dp) does not change the kind of the constant on the right.
What is printed?
integer :: i
i = -2.7
print *, i- -3
- -2
- -2.7
- Nothing: assigning a REAL to an INTEGER is a compile error
Assigning a REAL to an INTEGER variable is allowed and converts with int(), which truncates toward zero, giving -2. Rounding to -3 would need nint() (or floor() to always go down). Mixed-type assignment is legal Fortran; at most some compilers warn about possible loss of precision.
What does selected_real_kind(15, 307) return?
- A kind number for a real type with at least 15 decimal digits and exponent range 307 (8 on gfortran, but the value is compiler specific)
- Always the number of bytes of the type, i.e. 8
- A real number with 15 digits and exponent 307
- The value 15, the requested precision
The function returns a kind type parameter to use in declarations, e.g. integer, parameter :: dp = selected_real_kind(15, 307); real(dp) :: x. Kind numbers are just labels chosen by the compiler — gfortran happens to use bytes (8), but other compilers have used different numbering, which is why hard-coding real(8) is not portable. It returns a negative value if no such kind exists.
Which literal constant is double precision?
- 2.5e0
- 2.5
- 2.5f
- 2.5d0
The exponent letter d makes a real literal double precision (2.5d0 = 2.5 × 10^0). 2.5 and 2.5e0 are default (single) precision, and the C-style suffix f does not exist in Fortran. In modern code, kind suffixes such as 2.5_dp are preferred.
With integer, parameter :: dp = kind(1.0d0), what does the _dp in 1.0_dp mean?
- It sets the kind of the literal constant to dp
- It multiplies the constant by dp
- It is part of a variable name 1.0_dp
- It rounds the constant to dp decimal places
A suffix _k after a literal gives its kind type parameter, so 1.0_dp is a real constant of the same kind as double precision. Writing 1.0 without the suffix gives a default (single) real even when it is assigned to a real(dp) variable, losing precision before the assignment.
What does this print?
character(len=5) :: s
s = 'ab'
print *, len(s), len_trim(s), '[' // s // ']'- 5 2 [ab ]
- 2 2 [ab]
- 5 5 [ab ]
- 5 2 [ab]
A character(len=5) variable always holds exactly 5 characters: shorter values are padded with blanks on the right (longer ones are truncated). len gives the declared length 5, len_trim the length without trailing blanks, 2. To print without the padding use trim(s).
What does this print?
print *, 2**(-1), 2.0**(-1)- 0.5 and 0.5
- A compile error for 2**(-1)
- 0 and 0.5
- 1 and 0.5
An integer raised to an integer power stays INTEGER. 2**(-1) is defined as 1/(2**1) in integer arithmetic, which is 0. With a real base, 2.0**(-1) is 0.5. Expecting 0.5 from the integer form is the same trap as integer division.
Why is real(real64), with use iso_fortran_env, preferred over real(kind=8)?
- real(kind=8) is single precision on 64-bit systems
- Kind numbers are compiler specific: 8 often means 8 bytes but is not guaranteed, while real64 is a named constant giving a 64-bit real on any compiler
- real64 is faster because it uses vector registers
- kind=8 is rejected by all Fortran 2008 compilers
The standard only says kinds are positive integers chosen by the processor. Most compilers use the byte size, but some (e.g. the NAG compiler by default) number them 1, 2, 3, so real(8) could fail or mean something else. real64 from iso_fortran_env, or selected_real_kind(15, 307), states the requirement portably. kind=8 itself is still accepted by gfortran and ifx.
What is the size of a default integer on common compilers (gfortran, ifx)?
- 2 bytes (16 bits)
- 8 bytes (64 bits)
- 4 bytes (32 bits)
- It is always the machine word size of the CPU
The standard only says that default integer and default real occupy the same storage. In practice gfortran and ifx use 4 bytes, so huge(1) is 2147483647. Use selected_int_kind or iso_fortran_env (int64) when you need a larger range.
With character(len=5) :: s, what does s contain after s = 'abcdefgh'?
- 'abcde': the extra characters are cut off
- 'defgh': the last five characters are kept
- 'abcdefgh': the variable grows
- A runtime error is raised
A character variable has a fixed length. Assigning a longer string silently truncates it on the right, and assigning a shorter one pads it with blanks. There is no error, so a too-small len is a classic quiet bug.
After real :: x and x = 7 / 2, what does print *, x show?
- 3.50000000
- 4.00000000
- 3.00000000
- A compile error: integer and real are mixed
7 / 2 is an integer division and gives 3 first. Only then is the result converted to real for the assignment. Write 7.0 / 2 or 7 / 2.0 to get 3.5.
Arrays14
Given real :: a(5), which indices are valid?
- 0 to 4
- 0 to 5
- 1 to 5
- 1 to 4
Fortran arrays start at 1 unless you give an explicit lower bound, e.g. real :: a(0:4). Assuming 0-based indexing as in C or Python is a common source of off-by-one errors and out-of-bounds access (use -fcheck=bounds to catch them).
For real :: a(3,4), which element is stored in memory immediately after a(1,1)?
- a(1,2)
- a(2,2)
- a(1,4)
- a(2,1)
Fortran stores arrays in column-major order: the first index varies fastest, so the column a(1,1), a(2,1), a(3,1) comes first, then a(1,2) and so on. a(1,2) would be next in row-major languages like C — the opposite convention, which matters when passing arrays between the two.
What does this print?
integer :: i, a(10)
a = [(i*10, i = 1, 10)]
print *, a(2:8:3)- 20 30 40 50 60 70 80
- 20 50 80
- 20 50
- 30 60 90
The section a(start:end:stride) takes indices 2, 5, 8 — start at 2, step 3, never beyond 8. Since a(i) = 10*i, that gives 20 50 80. Unlike Python slices, the upper bound is inclusive, so 80 is included; '20 50' assumes an exclusive end.
What does b contain after the array assignment?
integer :: b(5)
b = [1, 2, 3, 4, 5]
b(2:5) = b(1:4)- 1 1 1 1 1
- 2 3 4 5 5
- 1 2 3 4 5
- 1 1 2 3 4
Array assignment semantics require the whole right-hand side to be evaluated before anything is stored, so overlapping sections behave as if a temporary copy were made: every element shifts right by one. '1 1 1 1 1' is what a naive loop do i = 2, 5; b(i) = b(i-1) produces, because each iteration reads a value already overwritten.
a is an allocatable array that is already allocated. What happens when allocate(a(n)) is executed again without stat=?
- A runtime error: an allocated array must be deallocated before it is allocated again
- The array is resized to n elements and the old values are kept
- The old memory is leaked silently and a new array is created
- The statement is ignored because the array is already allocated
Allocating an already allocated allocatable is an error condition; without stat= the program terminates (gfortran: 'Attempting to allocate already allocated variable'). Check allocated(a) first, or deallocate it. Allocatables never leak memory and allocate never resizes in place; for growing an array use a new allocation plus move_alloc, or assignment with reallocation.
a is a large real(n, n) array. Which loop nest accesses memory contiguously and is therefore usually faster?
- do j = 1, n; do i = 1, n; a(i, j) = 0.0 — the inner loop runs over the first index
- do i = 1, n; do j = 1, n; a(i, j) = 0.0 — the inner loop runs over the second index
- Both are equally fast because Fortran reorders all loops automatically
- Neither: whole-array assignment is always slower than loops
With column-major storage, consecutive values of the first index are adjacent in memory, so the innermost loop should vary i. Looping over j innermost jumps n elements per step and wastes cache lines — a common slowdown when C row-major habits are carried over. Compilers can interchange loops sometimes, but not reliably.
What does this print?
integer :: m(2,3)
m = reshape([1, 2, 3, 4, 5, 6], [2, 3])
print *, m(1,:)- 1 2 3
- 1 2
- 1 3 5
- 2 4 6
reshape fills the result in column-major order: column 1 gets 1, 2, column 2 gets 3, 4 and column 3 gets 5, 6. Row 1 is therefore 1 3 5. Expecting 1 2 3 assumes row-by-row filling as in C or NumPy's default; use reshape(..., order=[2,1]) for that.
What does this print?
real :: r(0:4, 3)
print *, size(r), size(r, 1), shape(r)- 15 5 5 3
- 12 4 4 3
- 15 4 4 3
- 15 5 3 5
The first dimension 0:4 has 5 elements (bounds are inclusive), the second has 3, so size(r) = 15, size(r, 1) = 5 and shape(r) is [5, 3]. Computing the extent as upper - lower (4) instead of upper - lower + 1 is the usual slip.
What does this print (Fortran 2003 or later)?
integer, allocatable :: c(:)
c = [1, 2, 3]
c = [c, 4]
print *, size(c)- 4
- 3
- A runtime error, because c is not allocated before the first assignment
- A compile error: an array cannot appear on both sides
Since Fortran 2003, assigning to a whole allocatable array automatically (re)allocates it to the shape of the right-hand side, so the first assignment allocates 3 elements and [c, 4] grows it to 4. This is convenient for appending, though it reallocates and copies every time, so it is slow inside a long loop.
What is y after the WHERE construct?
real :: x(3), y(3)
x = [4.0, -1.0, 9.0]
where (x > 0.0)
y = sqrt(x)
elsewhere
y = 0.0
end where- 2.0 0.0 3.0
- 2.0 NaN 3.0
- 0.0 0.0 0.0
- 2.0 1.0 3.0
where applies the assignment only to elements where the mask is true and elsewhere handles the rest, so sqrt is evaluated for 4 and 9 only. No NaN appears because sqrt is not applied to -1. It is the array counterpart of an if inside a loop.
After integer :: a(3) = [1, 2, 3] and the statement a(2:3) = a(1:2), what is a?
- [1, 1, 1]
- [2, 3, 3]
- [1, 1, 2]
- [1, 2, 3]: overlapping assignment is ignored
In an array assignment the whole right-hand side is evaluated before anything is stored, as if a temporary copy existed. So a(2) and a(3) receive the old a(1) and a(2), giving [1, 1, 2]. A hand-written loop going forward would give [1, 1, 1].
a = [1, 2, 3, 4, 5, 6]. What does print *, a(2:6:2) show?
- 2 3 4 5 6
- 2 4 6
- 2 6
- 1 3 5
An array section is first:last:stride and both ends are included. Starting at index 2 with stride 2 selects elements 2, 4 and 6, whose values are 2, 4 and 6.
Given real :: a(3, 4), what do size(a) and size(a, 2) return?
- 12 and 4
- 7 and 4
- 12 and 3
- 3 and 4
size(a) is the total number of elements, 3 * 4 = 12. size(a, dim) is the extent along one dimension, so size(a, 2) is 4 (and size(a, 1) would be 3). shape(a) returns both extents at once: [3, 4].
What does the program print?
real, allocatable :: a(:)
print *, allocated(a)
allocate(a(3))
print *, allocated(a)
deallocate(a)
print *, allocated(a)- T, T, T: deallocate only frees the elements
- F, T, F
- F, F, F: allocated is always false for a scalar-sized check
- A runtime error at the first print: a has no storage yet
allocated(a) is a safe query: it is false for an allocatable that has no storage yet (and the first print is legal, unlike touching a's elements), true after allocate and false again after deallocate. Calling deallocate on an array that is not allocated is an error, so check allocated first.
Control flow13
Which values of i does this loop print?
do i = 1, 10, 3
print *, i
end do- 1 4 7
- 1 3 6 9
- 1 4 7 10
- 3 6 9
The third value is the step: i starts at 1 and increases by 3 while it does not exceed the end value 10, giving 1, 4, 7, 10. The end value is inclusive, so 10 is printed; '1 4 7' assumes an exclusive end as in Python's range.
Inside a DO loop, what does the cycle statement do?
- Leaves the loop immediately
- Restarts the loop from its first iteration
- Repeats the current iteration with the same index
- Skips the rest of the current iteration and starts the next one
cycle is Fortran's continue: control jumps to the end of the loop body and the next iteration begins. Leaving the loop is exit (C's break). Mixing them up is common for programmers coming from C, where continue sounds like 'keep going'.
What is printed after the loop finishes normally?
integer :: i
do i = 1, 5
end do
print *, i- 5
- 0
- 6
- The value is undefined and depends on the compiler
When a DO loop completes, the loop variable keeps the value it had when the iteration count reached zero: it is incremented once more after the last iteration, so it equals 6 (end + step). The standard defines this, so it is not compiler dependent — though relying on it hurts readability. After an exit, it keeps the value at the time of exit.
What does this print?
select case (10)
case (:0)
print *, 'neg'
case (1:9)
print *, 'digit'
case default
print *, 'big'
end select- big
- digit
- neg
- Nothing, because no case range contains 10
case (:0) matches values up to 0 and case (1:9) values from 1 to 9 inclusive; 10 matches neither, so case default runs. Fortran's select case never falls through to the next case, and case default catches every value not listed — without it nothing would be printed.
What does this print?
count = 0
outer: do i = 1, 3
do j = 1, 3
if (j == 2) cycle outer
if (i == 3) exit outer
count = count + 1
end do
end do outer
print *, count- 3
- 4
- 2
- 6
cycle outer jumps to the next iteration of the outer loop, so for i = 1 and i = 2 only j = 1 is counted. For i = 3 the j = 1 pass hits exit outer, which leaves both loops before counting. Total 2. Getting 4 or 6 means treating cycle outer as a plain cycle of the inner loop.
How many times does the body of this loop run?
do i = 10, 1
print *, i
end do- 10 times, counting down
- 1 time
- 0 times
- Infinitely
The default step is +1, and when the start is already past the end the iteration count is zero, so the body never runs. To count down you must give a negative step: do i = 10, 1, -1.
What does this print?
n = 3
do i = 1, n
n = n + 1
end do
print *, i, n- 4 4
- 4 6
- An endless loop, nothing is printed
- 7 6
The iteration count of a DO loop is computed once, before the first iteration, from the start, end and step values. Changing n inside the body does not affect it, so the loop runs 3 times, n ends at 6 and i at 4. Expecting an endless loop is the C for-loop mental model, where the condition is re-evaluated.
Why can this test crash with an out-of-bounds access when i = 0?
if (i > 0 .and. a(i) > 0.0) then
print *, 'positive'
end if- .and. has lower precedence than >, so the expression is parsed wrongly
- a(i) is always evaluated first because Fortran evaluates right to left
- It cannot crash: Fortran stops at the first false operand
- Fortran does not guarantee short-circuit evaluation, so a(i) may be evaluated even when i > 0 is false
The standard lets the compiler evaluate the operands of .and. in any order and does not require skipping the second one, so a(0) may be read. Portable code nests the tests: if (i > 0) then; if (a(i) > 0.0) .... The precedence is fine (> binds tighter than .and.), and there is no fixed right-to-left rule either.
When is the condition of a do while loop checked?
do while (err > tol)
call iterate(x, err)
end do- After each iteration, so the body always runs at least once
- Before each iteration, so the body may run zero times
- Only once, before the first iteration
- Continuously, the loop stops in the middle of the body when it becomes false
do while tests the condition at the top of every iteration, like while in C. If err <= tol initially, the body is skipped. For a test after the body (do … until style), use an unbounded do with if (…) exit at the end.
In this FORTRAN 77 loop, what is the role of label 10?
DO 10 I = 1, N
S = S + A(I)
10 CONTINUE- It is the number of iterations
- It is the step size of the loop
- It marks the last statement of the loop body
- It is a jump target used only by GO TO
In DO 10 I = 1, N the label names the terminal statement of the loop; CONTINUE is a no-op commonly used for that purpose. Modern code writes do i = 1, n … end do and needs no labels. The iteration count comes from 1 and N, not from the label.
What does exit outer do inside the inner loop of this nest?
outer: do i = 1, 3
do j = 1, 3
if (i * j == 4) exit outer
end do
end do- It leaves only the inner loop, as a plain exit would
- It leaves both loops at once
- It restarts the outer loop from i = 1
- It stops the program
A construct name lets exit (and cycle) target an enclosing loop other than the innermost one. exit outer leaves the whole nest and continues after the matching end do outer. It replaces the GO TO that FORTRAN 77 code used for this.
With n = 3 and the construct below, which branch runs?
select case (n)
case (:0)
print *, 'A'
case (1:3)
print *, 'B'
case default
print *, 'C'
end select- A
- C, because the range 1:3 is exclusive at the top
- B and C, because select case falls through
- B
A case range includes both ends, so 1:3 matches 3. (:0) means every value up to 0. Unlike C's switch, select case never falls through: exactly one branch runs and there is no break statement.
How many times does the body of do i = 10, 1 run?
- Zero times
- 10 times, counting down
- Once
- It is a compile error, because the step is missing
The default step is +1, so a loop from 10 to 1 has max(0, (1 - 10 + 1) / 1) = 0 iterations. To count down, write do i = 10, 1, -1. A zero-trip loop is legal, and i is still set to 10 afterwards.
Procedures12
What is the main difference between a FUNCTION and a SUBROUTINE?
- A function returns a value and is used in an expression; a subroutine is invoked with CALL
- Only subroutines can take arguments
- Functions are always pure, subroutines may have side effects
- Only functions can be placed in modules
y = f(x) uses a function result inside an expression; call solve(a, b) invokes a subroutine, which passes results back through its arguments. Both take arguments, both can live in modules, and a function can have side effects unless declared pure.
A dummy argument is declared integer, intent(in) :: n. What happens if the procedure contains n = n + 1?
- The caller's variable is incremented
- Only a local copy is changed
- It runs, but the compiler prints a warning
- Compilation fails, because an intent(in) argument must not be modified
intent(in) is a promise checked by the compiler: the dummy may be read but not redefined, so the assignment is a compile-time error. Assuming a local copy is changed (as with C's pass-by-value) is the typical mistake — Fortran has no implicit copy, and without the intent the caller's variable really would be modified.
The internal subroutine tick is called three times. What is printed?
subroutine tick()
integer :: n = 0
n = n + 1
print *, n
end subroutine tick- 1, 1, 1
- 0, 0, 0
- A compile error: local variables cannot be initialized
- 1, 2, 3
Initializing a local variable in its declaration gives it the SAVE attribute implicitly: it is initialized once at program start and keeps its value between calls. It is not reset to 0 on every call as in C — that needs a separate executable statement n = 0. This is one of the most common traps for programmers coming from other languages.
A dummy argument is declared real, allocatable, intent(out) :: a(:). What happens to it on entry to the procedure?
- It is deallocated automatically if it was allocated, and its old values are lost
- It keeps its size and values; intent(out) only means it will be written
- It is reallocated with the same size and set to zero
- Nothing; intent(out) is ignored for allocatable arguments
intent(out) means the dummy becomes undefined on entry, and for an allocatable this is made concrete: it is deallocated. Code that reads the old size or values (assuming intent(out) works like intent(inout)) will crash or misbehave. Use intent(inout) if the procedure needs the incoming data.
Which statement is NOT allowed inside a PURE function?
- A call to another pure function
- Assigning to a local variable
- print *, 'debug', x
- Reading a module variable
A pure procedure must have no side effects: no external I/O and no modification of module variables or of its intent(in) arguments. It may read module variables, use locals and call other pure procedures. Debug prints are therefore rejected, which surprises people adding a quick print to an elemental or pure function.
Before Fortran 2018, what was required for a function to call itself?
- Nothing: all Fortran procedures were recursive by default
- Declaring it with the recursive prefix (and usually a result variable for the return value)
- Putting it in a module
- Declaring all local variables with save
Older compilers could allocate locals statically, so recursion had to be requested with recursive function fact(n) result(r). The result clause lets the function name be used for the recursive call instead of the result variable. Fortran 2018 made procedures recursive by default; save locals would actually break recursion by sharing state.
sq is declared elemental real function sq(x) with a scalar real, intent(in) :: x and sq = x*x. What does print *, sq([1.0, 2.0, 3.0]) do?
- Compile error: x is scalar but an array is passed
- Prints 1.0 4.0 9.0: an elemental function is applied to each element
- Prints 14.0, the sum of squares
- Prints 1.0, using only the first element
An elemental procedure is written for scalars but can be called with arrays (or conformable array/scalar mixes), and it is applied element by element, returning an array of the same shape. Elemental procedures are pure by default (unless declared impure). A plain non-elemental function with a scalar dummy would indeed reject the array.
inc is a module subroutine with integer, intent(inout) :: k that does k = k + 1. What happens with call inc(1)?
- A compile error: a constant cannot be passed as an intent(inout) argument
- It works and the constant 1 becomes 2 for the rest of the program
- It works; the change is made to a temporary copy
- A runtime warning is printed and the call is skipped
Arguments are passed by reference, so the dummy must be definable when it is intent(out) or intent(inout). With an explicit interface the compiler checks this: 'Non-variable expression in variable definition context'. In old code without interfaces such calls really could corrupt the 'constant' 1 or crash — another reason to use modules and intents.
A subroutine has integer, intent(in), optional :: n. How does it check whether n was passed?
- if (n /= 0)
- if (associated(n))
- if (present(n))
- if (allocated(n))
present() is the intrinsic for optional dummy arguments. Testing the value of an absent argument (n /= 0) is an invalid memory access that may crash. associated is for pointers and allocated for allocatables. Calls that omit an optional argument also require an explicit interface.
An array a(0:4) = [10, 20, 30, 40, 50] is passed to show. What is printed?
subroutine show(b)
integer, intent(in) :: b(:)
print *, lbound(b), ubound(b), b(1)
end subroutine show- 0 4 20
- 0 4 10
- 1 5 20
- 1 5 10
An assumed-shape dummy b(:) gets the shape of the actual argument but lower bound 1 unless you declare another (b(0:)). So b(1) is the first element, 10. Expecting the caller's bounds 0:4 inside the procedure (and b(1) = 20) is a frequent off-by-one bug.
inc has the dummy argument integer, intent(inout) :: k and an explicit interface (it is in a module). What happens with call inc(5)?
- The compiler rejects it: a constant cannot be passed to an intent(inout) dummy
- It works, and 5 becomes 6 inside the call
- It works, and the change is discarded afterwards
- It compiles, but crashes only if k is changed
intent(inout) and intent(out) arguments must be definable, so the actual argument has to be a variable. With an explicit interface the compiler checks this. In old external-procedure style, without an interface, passing a literal to a routine that writes to it could crash at run time.
What does this program print?
program p
call tick(); call tick(); call tick()
contains
subroutine tick()
integer :: n = 0
n = n + 1
print *, n
end subroutine
end program- 1 1 1 on three lines, since n is a fresh local each call
- 1 2 3 on three lines
- 0 1 2 on three lines
- A compile error: variables cannot be initialized in declarations
A local variable that is initialized in its declaration gets the SAVE attribute implicitly. The initialization happens once, and the value survives between calls, so the output is 1, 2, 3. To start from zero each time, declare integer :: n and write n = 0 as a separate statement. (The same trap exists with data statements.)
Modules and interfaces10
What is the effect of use linalg, only: solve?
- All public entities of linalg become accessible, and solve is compiled first
- solve becomes accessible and every other entity of linalg is made private
- Only the public entity solve from module linalg becomes accessible
- The program may call solve only once
The ONLY list restricts what is imported into the using scope, which avoids name clashes and documents dependencies. It does not change the module itself: other program units can still use everything public in linalg.
Where are procedures placed inside a module?
- Before the module statement
- After a contains statement, following the module's declarations
- Anywhere among the declarations
- In a separate file named after the module
A module has a specification part (variables, types, interfaces) and then, after contains, its module procedures. Placing procedures among the declarations is a syntax error, and Fortran has no rule that ties file names to module names.
A program does use shapes. Which entities of the module can it access?
module shapes
implicit none
private
public :: area
real, parameter :: pi = 3.14159
contains
real function area(r)
real, intent(in) :: r
area = pi * r * r
end function area
end module shapes- area and pi
- Nothing, because the module is private
- pi only
- Only area
The bare private statement changes the default accessibility of the module to private, and public :: area then exports just that function. pi is still used internally by area but cannot be referenced from outside. A private statement does not hide the module itself, only the entities not listed as public.
Compiling main.f90 (which does use solver) fails with 'Cannot open module file solver.mod'. What is the usual cause?
- The use statement must come after implicit none
- solver.f90 has not been compiled yet; the module must be compiled before the files that use it
- Module names must match the file name main.f90
- Modules can only be used from inside other modules
Compiling a module produces a .mod file describing its interface, and the compiler reads it when it sees use solver. So compilation order matters: gfortran -c solver.f90 first, then main.f90 (build tools resolve this order automatically). use must come before implicit none, not after.
An external subroutine (not in a module, no interface block) declares real, intent(in) :: a(:). It is called as call stats(x). Why can this give garbage results?
- Arrays cannot be passed to external subroutines
- An assumed-shape dummy requires an explicit interface; without it the caller passes only an address, not the array descriptor
- intent(in) arrays are copied element by element and lose their size
- Assumed-shape arrays must be allocatable in the caller
With a(:) the callee expects a descriptor carrying bounds and strides. Without an explicit interface the caller assumes an old-style call and passes just the address, so the callee reads nonsense sizes. The fix is to put the procedure in a module (or internal procedure) or write an interface block — this is a main reason to use modules.
What is the recommended modern replacement for FORTRAN 77 COMMON blocks to share data between program units?
- Global variables declared in the main program
- EQUIVALENCE statements
- Module variables accessed with use
- Passing everything through files
Variables declared in a module are shared by every unit that uses it, with type checking and a single declaration. COMMON relies on each unit repeating the layout, and mismatches silently corrupt data. Main-program variables are not visible to external procedures, and EQUIVALENCE only overlays storage.
What does use constants, only: g => gravity do?
- Assigns the value of g to gravity
- Imports the module variable gravity under the local name g
- Imports both g and gravity
- Creates a pointer g that points to gravity
local_name => module_name renames an entity on import, typically to avoid a clash with a local name or another module. Only the name changes; g refers to the same object, and gravity is not visible under its original name in that scope. Despite the arrow, it has nothing to do with pointer assignment.
Module norms defines a generic interface describe with specific subroutines for an integer and a default real argument. What happens with call describe(2.5d0)?
interface describe
module procedure describe_int, describe_real
end interface describe- 2.5d0 is converted to default real and describe_real is called
- describe_int is called with 2
- The first procedure in the list is called
- A compile error: there is no specific subroutine for that argument type and kind
Generic resolution picks the specific procedure whose dummy arguments match the actual arguments' type, kind and rank exactly; no conversion is applied. A double precision argument matches neither, so gfortran reports 'There is no specific subroutine for the generic'. Add a describe_dp version to support it.
A module declares integer, protected :: nsteps = 10. What can a program that uses the module do with nsteps?
- Neither read nor assign it
- Read and assign it, like any public variable
- Read it, but not assign to it
- Assign it only once
protected (Fortran 2003) makes a public module variable read-only outside the module: assignments in using units are compile-time errors ('PROTECTED ... cannot appear in a variable definition context'), while procedures of the module itself can still change it. Making it private would hide it completely.
What is the main benefit of placing a procedure in a module instead of writing it as an external procedure?
- It gets an explicit interface automatically, so the compiler checks the number, type and kind of arguments
- Module procedures run faster because they are always inlined
- Module procedures can be called without the CALL keyword
- Only module procedures may have array arguments
When a unit uses the module, the compiler knows each procedure's interface and can reject mismatched calls, and features like assumed-shape arrays, optional and keyword arguments work. External procedures without an interface block are called blindly, so mistakes show up as wrong results at runtime.
I/O13
In print *, x, what does the asterisk mean?
- Print x to all open units
- Multiply x by the default unit number
- Print x without a trailing newline
- List-directed formatting: the compiler chooses the layout of the values
The * stands for the format: list-directed output, where the processor chooses widths and separators. It is convenient but layout differs between compilers. For exact layout give a format string, e.g. print '(F8.3)', x. In write(*,*) the first * is the default output unit and the second the format.
What does write(*,'(F8.3)') 3.14159 output?
- 3.14159 in 8 columns
- 3.141 (truncated, not rounded)
- 3.142 left-aligned followed by 3 blanks
- 3.142 right-aligned in 8 columns (3 leading blanks)
Fw.d prints a real in w = 8 columns with d = 3 digits after the decimal point, rounding the value and right-justifying it: ' 3.142'. The width counts the sign, digits and the point. Expecting truncation (3.141) or left alignment is the usual misreading of the descriptor.
What does write(*,'(F6.2)') -123.456 output?
- -123.46
- ******
- -123.5
- -23.46
'-123.46' needs 7 characters (sign, three digits, point, two decimals), but the field is only 6 wide. Fortran never widens a field or silently drops digits: it fills the whole field with asterisks. Forgetting that the minus sign takes a column is the usual cause.
The input contains two lines: '1 2' and '3 4'. What does the program print?
read(*,*) a
read(*,*) b
print *, a, b- 1 2
- 3 4
- 1 3
- 2 3
Each READ statement starts at a new record (line). The first read takes 1 and discards the rest of the line, including 2; the second read starts on the next line and gets 3. To read both values from one line use a single read(*,*) a, b.
What happens with open(unit=10, file='data.txt', status='old') if data.txt does not exist?
- An empty data.txt is created
- An error: status='old' requires the file to exist (catch it with iostat=)
- The open succeeds and the first read returns zeros
- The program waits until the file is created
status='old' means the file must already exist; status='new' requires it not to exist, 'replace' creates or overwrites, and 'unknown' (the default) is processor dependent, usually creating it. Without iostat= or err= the failed OPEN terminates the program; with iostat= you get a non-zero code and can report the problem.
Which edit descriptor writes a character string in a format?
- I
- F
- S
- A
A is for character data, e.g. write(*,'(A, I5)') 'n =', n. I is for integers and F for reals in fixed-point notation; S is a sign-control descriptor, not a string descriptor. Using I or F for a string causes a runtime format error.
Which statement is equivalent to print *, x?
- write(6) x
- write(*,*) x
- read(*,*) x
- write(x,*)
In write(*,*) the first * is the default output unit and the second asks for list-directed formatting, exactly like print *. write(6) x without a format is unformatted (binary) output to unit 6, and write(x,*) treats x as the unit.
What does write(*,'(E10.3)') 12345.678 output?
- 1.235E+04
- 0.123E+05
- 12345.678
- 1.23E+04
The E descriptor writes a mantissa between 0.1 and 1 with d = 3 significant digits after the point, so 12345.678 becomes 0.123E+05 (right-aligned in 10 columns). The familiar 1.235E+04 form is produced by the ES (scientific) descriptor, ES10.3.
How many lines does this statement write?
write(*,'(3I4)') (i, i = 1, 7)- 1
- 7
- 3
- A runtime error, because the format has room for only 3 values
When the output list is longer than the format, format reversion starts a new record and reuses the format: 1 2 3, then 4 5 6, then 7. That is three lines. A format with too few descriptors is not an error, and the whole list is never forced onto one line.
read(unit, *, iostat=ios) x reaches the end of the file. What is ios?
- 0
- A positive error code
- The number of values read
- A negative value (equal to iostat_end from iso_fortran_env)
iostat is 0 on success, positive on an error and negative on end-of-file or end-of-record; the exact end-of-file value is iostat_end (-1 in gfortran). A typical read loop is do; read(u,*,iostat=ios) x; if (ios /= 0) exit; … end do. Treating any non-zero value as an error hides the normal end of the data.
What does write(*, '(I5.3)') 7 output?
- ' 7'
- '00007'
- ' 007'
- '7.000'
In Iw.m the width w is 5 and the minimum number of digits m is 3, so the value is padded with leading zeros to 007 and then with blanks on the left up to 5 characters: ' 007'. Plain I5 would give ' 7'.
What does write(*, '(A, I0)') 'n=', 42 output?
- n=42
- n= 42
- n=0
- n=42.0
I0 (Fortran 95 and later) uses the minimal width that fits the number, with no leading blanks. It is handy for tidy output and for turning integers into text, where a fixed width such as I5 would leave spaces.
What does this program print?
character(len=10) :: s
write(s, '(I0)') 123
print *, trim(s) // '!'- 123!
- 123 !
- A runtime error: write needs a unit number, not a variable
- Nothing: write to a variable prints no text
An internal write uses a character variable as the file, which is the Fortran way to convert a number to a string. s becomes '123' followed by seven blanks. trim removes the trailing blanks, so the concatenation gives 123!. The reverse conversion is an internal read.
Intrinsic functions12
a and b are real 2×2 arrays. What does c = a * b compute?
- The element-by-element product, c(i,j) = a(i,j) * b(i,j)
- The matrix product of a and b
- The dot product of a and b
- A compile error, because * is not defined for arrays
All arithmetic operators work element-wise on conformable arrays in Fortran. The linear-algebra product is matmul(a, b), and dot_product works on vectors. Using * where matmul was intended compiles without complaint and gives wrong numbers, which is why it is a classic mistake.
What does this print?
print *, mod(-7, 3), modulo(-7, 3)- 2 2
- -1 2
- -1 -1
- 2 -1
mod(a, p) is a - int(a/p)*p, so its result has the sign of a: -7 - (-2)*3 = -1. modulo(a, p) is a - floor(a/p)*p and has the sign of p: -7 - (-3)*3 = 2. For periodic indices (e.g. wrapping grid points) you usually want modulo; using mod gives negative indices.
What does this print?
integer :: m(2,3)
m = reshape([1, 2, 3, 4, 5, 6], [2, 3])
print *, sum(m, dim=1)- 9 12
- 21
- 3 7 11
- 6 15
reshape fills m column by column: columns are (1,2), (3,4), (5,6). dim=1 sums along the first index, i.e. down each column, giving one value per column: 3 7 11. '9 12' would be dim=2 (row sums), and 21 is the plain sum(m).
What happens when compiling print *, sqrt(2)?
- A compile error: sqrt requires a REAL or COMPLEX argument
- It prints 1.41421354
- It prints 1, the integer square root
- It prints 1.4142135623730951 in double precision
sqrt is generic over REAL and COMPLEX kinds only; there is no INTEGER version and no automatic conversion of intrinsic arguments, so gfortran reports "'x' argument of 'sqrt' intrinsic must be REAL or COMPLEX". Write sqrt(2.0), sqrt(2.0_dp) or sqrt(real(n, dp)).
What does this print?
print *, int(-2.5), nint(-2.5), floor(-2.5), ceiling(-2.5)- -2 -3 -3 -2
- -3 -3 -3 -2
- -2 -2 -3 -2
- -2 -3 -2 -3
int truncates toward zero (-2); nint rounds to the nearest integer with halves going away from zero (-3, not banker's rounding to -2); floor goes down (-3) and ceiling goes up (-2). Treating int as floor is the usual bug with negative values.
What does dot_product([1, 2, 3], [4, 5, 6]) return?
- [4, 10, 18]
- 21
- 90
- 32
dot_product multiplies corresponding elements and sums them: 1*4 + 2*5 + 3*6 = 32. [4, 10, 18] is the element-wise product a * b, before summing. For real vectors it is sum(a*b); for complex ones it conjugates the first argument.
A has shape (2, 3) and B has shape (3, 4). What is the shape of matmul(A, B)?
- (2, 4)
- (3, 3)
- (2, 3)
- matmul is not defined for these shapes
As in linear algebra, an m×k matrix times a k×n matrix gives m×n. The inner dimensions (3 and 3) must match, which they do, and the result takes the outer ones: 2×4.
What does this print?
print *, maxval([3, 9, 2, 9]), maxloc([3, 9, 2, 9])- 9 4
- 9 2
- 2 9
- 9 2 4
maxval returns the largest value and maxloc its position. When the maximum occurs more than once, maxloc returns the first occurrence (index 2) unless back=.true. is given. maxloc always returns a rank-1 array (one element per dimension), so assign it to an array or use maxloc(a, dim=1) for a scalar.
b is an integer array with no negative elements. What does maxval(b, mask=b < 0) return (gfortran, default integer)?
- 0
- The largest element of b
- A runtime error for an empty selection
- -2147483648, the most negative integer, because the masked set is empty
For an empty set, maxval returns the negative number of largest magnitude for the type (minval returns the largest positive, huge). There is no error, so code that finds 'the largest negative value' must check count(b < 0) > 0 first, or it will get this sentinel.
Which intrinsic returns how many elements of array a are positive?
- size(a > 0)
- count(a > 0)
- sum(a > 0)
- any(a > 0)
count takes a logical array and returns the number of .true. elements. size(a > 0) just gives the total number of elements, sum does not accept logical arrays, and any returns a single logical saying whether at least one element is true.
What do mod(-7, 3) and modulo(-7, 3) return?
- 2 and 2
- -1 and 2
- -1 and -1
- 2 and -1
mod takes the sign of its first argument: -7 = -2*3 + (-1). modulo takes the sign of the second argument: -7 = -3*3 + 2. For positive operands they agree, which hides the difference until a negative index appears.
What do len('ab ') and len_trim('ab ') return?
- 2 and 2
- 5 and 5
- 2 and 5
- 5 and 2
len counts every character of the string, trailing blanks included: 5. len_trim ignores the trailing blanks: 2. Because shorter strings are blank-padded, len_trim (or trim) is how you get the 'real' length of a text stored in a fixed-length variable.
Numerics13
Why is the REAL value stored for 0.1 not exactly one tenth?
- Fortran stores reals in decimal with only 6 digits
- Default reals are rounded to 1 decimal place
- 0.1 has no finite binary representation, so it is rounded to the nearest representable value
- Only single precision has this problem; double precision stores 0.1 exactly
Floating-point numbers are binary fractions, and 1/10 is a repeating fraction in base 2, just as 1/3 is in base 10. Every precision rounds it — double precision just has a smaller error. This is why reals should not be compared with ==.
What is the value of x?
real :: x
x = 1/3 * 3.0- 0.0
- 1.0
- 0.999999
- 3.0
Operators of equal precedence are evaluated left to right, so 1/3 is computed first — integer division giving 0 — and only then multiplied by 3.0. Mixed-mode conversion happens per operation, not for the whole expression. Write 1.0/3.0 * 3.0 or reorder the expression.
What does epsilon(1.0) return?
- The smallest positive normal real, about 1.18e-38
- The default tolerance used by == for reals
- The spacing between 1.0 and the next larger real, about 1.19e-7 for single precision
- The largest relative rounding error in any computation
epsilon(x) is the machine epsilon for the kind of x: 2**(-23) ≈ 1.19e-7 for single, 2**(-52) ≈ 2.2e-16 for double. It is the right scale for relative tolerances such as abs(a-b) <= 4*epsilon(a)*abs(a). The smallest positive normal number is tiny(x); == has no built-in tolerance.
x and y are default (single precision) REAL. What does this print?
x = 1.0e8
y = x + 1.0
print *, y == x- T
- F
- Nothing: the addition overflows
- It depends on whether x was declared double precision
Single precision has a 24-bit mantissa, so above 2**24 ≈ 1.68e7 consecutive representable values are more than 1 apart; near 1e8 the spacing is 8. 1e8 + 1 rounds back to 1e8 and the comparison is true. This absorption is why adding many small terms to a large running sum loses them — sum in double precision or use compensated summation.
With default gfortran settings, what does this print?
real :: x, y
x = huge(x)
y = x * 2
print *, y- The same value as huge(x)
- 0.0
- -3.40282347E+38
- Infinity
Floating-point overflow follows IEEE arithmetic: the result becomes +Infinity and, by default, execution continues without an error (gfortran can trap it with -ffpe-trap=overflow). Values do not wrap around like integers, and they do not saturate at huge(x).
What is the robust way to test whether two computed REAL values a and b are equal?
- a == b
- int(a) == int(b)
- abs(a - b) <= tol * max(abs(a), abs(b)) with a small relative tolerance
- nint(a * 1000) == nint(b * 1000) in every case
Rounding errors make values that are mathematically equal differ in the last bits, so == often fails. A relative tolerance (e.g. a few times epsilon(a), or problem-specific) scales with the magnitude of the numbers. Truncating with int or rounding to fixed decimals hides real differences and still fails near rounding boundaries.
What does this print?
integer :: i, n
i = 7
n = 2
print *, real(i/n), real(i)/n- 3.0 and 3.5
- 3.5 and 3.5
- 3.0 and 3.0
- 4.0 and 3.5
real(i/n) converts too late: i/n is computed first as integer division (3) and only the result is turned into 3.0. real(i)/n converts before dividing, so the division is done in real arithmetic and gives 3.5. Where the conversion goes is what matters in mixed-mode expressions.
i is a default integer. What does this print with gfortran (no -ftrapv)?
i = huge(i)
i = i + 1
print *, i- 2147483648
- Typically -2147483648: overflow is undefined by the standard and usually wraps silently
- Infinity
- A runtime error: integer overflow
Default integers are 32-bit with huge(i) = 2147483647. Integer overflow is not defined by the Fortran standard; in practice the value wraps to -2147483648 with no warning (and optimizers may assume it never happens). Unlike reals, integers have no Infinity. Use a 64-bit kind (int64) for large counters.
What does this print?
print *, 0.1 + 0.2 == 0.3, 0.1d0 + 0.2d0 == 0.3d0- F F
- T T
- T F
- F T
Whether equality holds depends on how each value rounds in the given precision. In single precision, 0.1 + 0.2 happens to round to the same float as 0.3, so the test is true; in double precision the sum is 0.30000000000000004 and the test is false. Assuming higher precision makes == safer is the trap — neither result can be relied on.
x is a REAL variable holding -8.0. What does print *, x**(1.0/3.0) show?
- NaN
- -2.0
- 2.0
- A compile error
A real power with a non-integer exponent is computed as exp(y*log(x)), and the log of a negative number is not real, so the result is NaN. Mathematically the real cube root is -2, but you have to write -abs(x)**(1.0/3.0) (or sign(abs(x)**(1.0/3.0), x)). An integer exponent such as x**3 works fine for negative x.
What does print *, 2**3**2 show?
- 64
- 512
- 36
- A compile error: chained ** is not allowed
The ** operator is right-associative, so 2**3**2 means 2**(3**2) = 2**9 = 512. Left-to-right evaluation, (2**3)**2 = 64, would be the rule for most other operators.
What does print *, 7 / 2 * 2.0 show?
- 7.00000000
- 6.00000000
- 1.75000000
- 0.00000000
/ and * have equal priority and are evaluated left to right: 7 / 2 is integer division = 3, then 3 * 2.0 = 6.0. Putting the real operand first, 2.0 * 7 / 2, would give 7.0.
What does print *, huge(1) show on a typical compiler, where the default integer is 4 bytes?
- 2147483647
- 4294967295
- 32767
- 9223372036854775807
Fortran integers are signed, so a 32-bit one holds up to 2**31 - 1 = 2147483647. Unsigned 4294967295 does not exist in standard Fortran, 32767 is a 2-byte integer and 9223372036854775807 is huge(1_int64).
Parallel and modern features10
Given type(particle) :: p, where particle has a component mass, how do you access it?
- p.mass
- p%mass
- p->mass
- mass(p)
Fortran uses % as the component selector. p.mass is a C/Python habit; a few compilers accept it as a vendor extension (gfortran only with -fdec-structure), but it is not standard because it is ambiguous with operators like .and., so portable code uses %.
Code with !$omp parallel do directives is compiled without -fopenmp. What happens?
- Compilation fails with an unknown-directive error
- The loop still runs in parallel using default settings
- The loop is skipped
- The directives are treated as ordinary comments and the loop runs serially
OpenMP directives start with !$omp, which is a comment to any compiler that has OpenMP disabled. That is a deliberate design choice: the same source builds as a serial program. The same applies to lines starting with the !$ conditional-compilation sentinel.
What does do concurrent (i = 1:n) guarantee?
- The iterations always run in parallel on all CPU cores
- It creates n threads, one per iteration
- It tells the compiler the iterations are independent and may run in any order; it does not guarantee parallel execution
- The compiler checks that there are no data races and stops otherwise
do concurrent is an assertion by the programmer, enabling vectorization or parallelization (e.g. with -ftree-parallelize-loops or GPU offload) but not requiring it. The compiler cannot fully verify independence, so a loop that writes and reads the same element across iterations gives undefined results rather than an error.
What is wrong with this OpenMP loop, and what fixes it?
s = 0.0
!$omp parallel do
do i = 1, n
s = s + a(i)
end do
!$omp end parallel do- The loop index i must be declared private, otherwise the loop fails
- OpenMP cannot parallelize loops that read arrays; nothing fixes it
- s must be declared double precision for OpenMP
- All threads update the shared s at once (a data race); add reduction(+:s)
s is shared by default, so concurrent read-modify-write updates are lost and the result varies between runs. reduction(+:s) gives each thread a private partial sum and combines them at the end. The loop index of a parallel do is private automatically, so that is not the problem.
Image 1 assigns x[2] = 5.0 to a coarray, and image 2 then prints x. What is needed so image 2 is guaranteed to print 5.0?
- A synchronization, e.g. sync all, executed by both images between the write and the read
- Nothing: coarray assignments are visible to all images immediately
- Declaring x with the volatile attribute
- Running the program with a single image
Coarray images run asynchronously; without an image-control statement (sync all, sync images, or locks/events) there is no ordering between the remote write and the read, so image 2 may print the old value. sync all ends a segment on every image, after which the write is guaranteed to be visible. A single image would never execute x[2] at all.
Given type :: point; real :: x, y; end type, how can a value be created in one expression?
- p = new point(1.0, 2.0)
- p = {1.0, 2.0}
- p = point(1.0, 2.0)
- p = point%(1.0, 2.0)
Every derived type has an intrinsic structure constructor with the type's name, taking the components in order (or as keywords: point(x=1.0, y=2.0)). Fortran has no new operator — objects are ordinary variables — and brace initializers are C syntax.
type, extends(shape) :: circle is declared. Which statement is true?
- circle inherits all components and type-bound procedures of shape and can override the procedures
- circle can only access the public procedures of shape, not its components
- A variable of type(shape) can hold a circle value
- extends copies shape's source code into circle at compile time
extends creates a derived type that inherits components and bindings, and it can override type-bound procedures. Polymorphism needs class(shape), not type(shape): a class(shape) dummy or allocatable can hold a circle, while type(shape) is exactly shape. Confusing type() and class() is the usual mistake.
tmp is declared in the enclosing routine and used as a scratch variable inside an OpenMP parallel do. What is the problem, and the fix?
!$omp parallel do
do i = 1, n
tmp = a(i) * 2.0
b(i) = tmp + 1.0
end do
!$omp end parallel do- b must be declared private, otherwise results are lost
- There is no problem because each statement is atomic
- The loop index i must be declared shared
- tmp is shared by default, so threads overwrite each other's value; declare it private(tmp)
Variables declared outside the parallel region are shared unless stated otherwise; only the loop index is made private automatically. Between one thread's tmp = ... and its use, another thread may overwrite tmp, giving wrong b values that vary between runs. private(tmp), or default(none) with explicit clauses, fixes it. b should stay shared because each thread writes different elements.
A program declares the coarray real :: x[*]. In an expression, what does x[2] refer to?
- The second element of the array x
- x multiplied by 2
- The copy of x that lives on image 2
- The x of the image whose this_image() value is 1 more than the current one
A coarray has one copy per image (process); square brackets select the image, round brackets the array element. x without brackets is the local copy, x[2] the copy on image 2, which may be on another node. this_image() and num_images() give the current image number and the total.
What does this print?
type :: vec
real, allocatable :: v(:)
end type vec
type(vec) :: a, b
a%v = [1.0, 2.0, 3.0]
b = a
b%v(1) = 99.0
print *, a%v(1), b%v(1)- 99.0 99.0
- 1.0 99.0
- 1.0 1.0
- A runtime error: b%v is not allocated
Intrinsic assignment of a derived type copies allocatable components deeply: b%v is allocated and gets its own copy of the data, so changing it does not affect a. With pointer components only the pointer would be copied and both objects would see 99.0 — the shallow copy behaviour people often expect here.
Как проходить тест
- Выберите темы и уровень — лёгкий уровень проверяет определения и задачи в одно действие, средний — стандартные вычисления, сложный — многошаговые задачи и теорию.
- Отвечайте касанием или с клавиатуры: 1–4 или A–D, Enter — следующий вопрос.
- Читайте объяснения — после ошибки разбор открывается сразу, после верного ответа его можно раскрыть кнопкой «Почему».
- Работайте над ошибками — «Повторить ошибки» в конце теста или режим «Только мои ошибки» потом: ответы запоминаются в этом браузере.
Незавершённый тест сохраняется — после перезагрузки страницы можно продолжить с того же вопроса.
Темы теста
- Program structure 10
- Types and kinds 13
- Arrays 14
- Control flow 13
- Procedures 12
- Modules and interfaces 10
- I/O 13
- Intrinsic functions 12
- Numerics 13
- Parallel and modern features 10
Другие тесты
Тест по линейной алгебре160 вопросовТест по дифференциальным уравнениям130 вопросовТест по теории вероятностей и статистике130 вопросовТест по SAS100 вопросовТест по языку R100 вопросовТест по LaTeX100 вопросовТест по системам компьютерной алгебры100 вопросовТест по языку C100 вопросовТест по COBOL100 вопросовТест по MATLAB100 вопросовТест по PowerBuilder100 вопросовТест по UNIX100 вопросов
