100 Fortran Interview Questions and Answers (2026)
The most asked Fortran interview questions with structured answers — a quick answer, a clear explanation and working code for each. Covers basics for freshers through advanced, scenario and coding questions for experienced developers.
Updated November 2026 Reviewed by Abhishek Kumar 120 min read
Quick answerFortran (FORmula TRANslation) is a high-level programming language designed for scientific and engineering computations. It is one of the oldest programming languages, still widely used in high-performance computing.
Scientific Computing: Optimized for numerical computations
Quick answerFortran provides a rich set of data types including integers, reals, characters, logicals, and derived types. All types are statically typed.
Integer: INTEGER
Real: REAL
Character: CHARACTER
Logical: LOGICAL
Derived Types: User-defined types
Fortran
! Data Types in Fortranprogram datatypes
implicitnoneinteger :: age = 25real :: salary = 50000.50real :: pi = 3.14159265358979character :: grade = 'A'logical :: isActive = .true.character(len=10) :: name = "Alice"real :: price = 99.99print *, "Age: ", age
print *, "Salary: ", salary
print *, "Pi: ", pi
print *, "Grade: ", grade
print *, "Active: ", isActive
print *, "Name: ", nameprint *, "Price: ", price
endprogram datatypes
Quick answerArrays in Fortran are powerful data structures for storing collections of values. Fortran supports both static and dynamic arrays with extensive array operations.
Quick answerDerived Types are user-defined data structures that group related data together. They are similar to structs in C and records in other languages.
Quick answerModules are program units that encapsulate data, procedures, and derived types. They provide a way to organize code and control visibility.
Module Definition: MODULE math_utils
Contains: CONTAINS section for procedures
Use: USE module_name
Visibility: PRIVATE and PUBLIC attributes
Module Procedures: Procedures defined within modules
Fortran
! Modules in Fortranmodule math_constants
implicitnonereal, parameter :: PI = 3.14159265358979real, parameter :: E = 2.71828182845905endmodule math_constants
module geometry
use math_constants
implicitnonecontainsfunction circle_area(radius) result(area)
real, intent(in) :: radius
real :: area
area = PI * radius * radius
endfunction circle_area
function circle_circumference(radius) result(circ)
real, intent(in) :: radius
real :: circ
circ = 2.0 * PI * radius
endfunction circle_circumference
endmodule geometry
program test_geometry
use geometry
implicitnonereal :: r = 5.0print *, "Circle area: ", circle_area(r)
print *, "Circle circumference: ", circle_circumference(r)
endprogram test_geometry
Quick answerPointers in Fortran provide a way to reference data indirectly. They are useful for dynamic data structures and efficient memory management.
Quick answerFortran provides IF, DO, DO WHILE, and SELECT CASE statements for controlling program flow.
IF Statement: IF (condition) THEN ... ELSE ... END IF
DO Loop: DO i = 1, 10 ... END DO
DO WHILE: DO WHILE (condition) ... END DO
SELECT CASE: SELECT CASE(value) ... END SELECT
EXIT/CYCLE: Loop control statements
Fortran
! Control Structures in Fortranprogram control_structures
implicitnoneinteger :: i, num
logical :: found
! IF statement
num = 10if (num > 0) thenprint *, "num is positive"elseif (num < 0) thenprint *, "num is negative"elseprint *, "num is zero"endif! DO loopdo i = 1, 10print *, "i = ", i
enddo! DO WHILE loop
i = 1dowhile (i <= 5)
print *, "while i = ", i
i = i + 1enddo! SELECT CASEselectcase(num)
case(0)
print *, "num is zero"case(1:5)
print *, "num between 1 and 5"casedefaultprint *, "num is greater than 5"endselectendprogram control_structures
Quick answerSubroutines and Functions are procedures that encapsulate code for reuse. Functions return a value, while subroutines do not.
Function: FUNCTION name(args) RESULT(result)
Subroutine: SUBROUTINE name(args)
Intent: INTENT(IN), INTENT(OUT), INTENT(INOUT)
Optional Arguments: OPTIONAL attribute
Recursive: RECURSIVE attribute
Fortran
! Subroutines and Functionsmodule math_ops
contains! Function returning a valuefunction multiply(a, b) result(product)
integer, intent(in) :: a, b
integer :: productproduct = a * b
endfunction multiply
! Subroutine with intentsubroutine divide(a, b, quotient, remainder)
integer, intent(in) :: a, b
integer, intent(out) :: quotient, remainder
quotient = a / b
remainder = mod(a, b)
endsubroutine divide
! Function with optional argumentsfunction power(base, exponent) result(result)
real, intent(in) :: base
integer, optional, intent(in) :: exponentreal :: result
integer :: expif (present(exponent)) thenexp = exponentelseexp = 2endif
result = base ** expendfunction power
endmodule math_ops
program test_ops
use math_ops
implicitnoneinteger :: q, r
print *, "Multiply: ", multiply(5, 4)
call divide(10, 3, q, r)
print *, "Quotient: ", q, " Remainder: ", r
print *, "Power: ", power(2.0, 3)
print *, "Power default: ", power(2.0)
endprogram test_ops
Quick answerError Handling in Fortran uses IOSTAT for file operations, and STAT for allocation and deallocation errors.
IOSTAT: READ(10, *, IOSTAT=ios) x
STAT: ALLOCATE(arr(10), STAT=status)
ERRMSG: ALLOCATE(arr(10), ERRMSG=msg)
Deallocation: DEALLOCATE(arr, STAT=status)
Prevention: Check conditions before operations
Fortran
! Error Handling in Fortranprogram error_handling
implicitnoneinteger :: ios, unit, i
real :: x
! File error handling
open(unit=10, file="nonexistent.txt", status="old", iostat=ios)
if (ios /= 0) thenprint *, "Error opening file: ", ios
else
close(10)
endif! Read error handling
open(unit=10, file="numbers.txt", status="old", action="read", iostat=ios)
if (ios == 0) thendo i = 1, 5
read(10, *, iostat=ios) x
if (ios /= 0) thenprint *, "Error reading at line: ", i
exitendifprint *, x
enddo
close(10)
endif! Division by zerointeger :: a = 10, b = 0if (b /= 0) thenprint *, a / b
elseprint *, "Division by zero prevented"endifendprogram error_handling
Quick answerPure Functions have no side effects and can be used in parallel computations. Elemental Functions operate on arrays element-wise.
Pure: PURE FUNCTION square(x)
Elemental: ELEMENTAL FUNCTION cube(x)
No Side Effects: Cannot modify global state
Array Operations: Elemental functions work on arrays
Parallelism: Suitable for parallel processing
Fortran
! Pure and Elemental Functionsmodule pure_functions
contains! Pure function - no side effectspurefunction square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
endfunction square
! Elemental function - works on arrays element-wiseelementalrealfunction cube(x)
real, intent(in) :: x
cube = x * x * x
endfunction cube
endmodule pure_functions
program test_pure
use pure_functions
implicitnonereal :: arr(5) = [1.0, 2.0, 3.0, 4.0, 5.0]
real :: arr2(5)
arr2 = square(arr)
print *, "Squares: ", arr2
arr2 = cube(arr)
print *, "Cubes: ", arr2
endprogram test_pure
Quick answerGeneric Interfaces allow multiple procedures to share the same name, with the compiler selecting the appropriate one based on argument types.
! Generic Interfaces in Fortranmodule generic_math
interface add
moduleprocedure add_int, add_real
endinterface add
containsfunction add_int(a, b) result(c)
integer, intent(in) :: a, b
integer :: c
c = a + b
endfunction add_int
function add_real(a, b) result(c)
real, intent(in) :: a, b
real :: c
c = a + b
endfunction add_real
endmodule generic_math
program test_generic
use generic_math
implicitnoneprint *, "Integer add: ", add(5, 3)
print *, "Real add: ", add(5.5, 3.2)
endprogram test_generic
Quick answerType Casting converts values between different data types using intrinsic functions like REAL, INT, CHAR, and CMPLX.
Integer to Real: REAL(i)
Real to Integer: INT(r)
String to Integer: READ(str, *) i
Integer to String: WRITE(str, *) i
Complex: CMPLX(real_part, imag_part)
Fortran
! Type Casting and Conversionprogram type_conversion
implicitnoneinteger :: i = 42real :: r
complex :: c
! Integer to real
r = real(i)
print *, "Integer to real: ", r
! Real to integer (truncates)
r = 3.14159
i = int(r)
print *, "Real to integer: ", i
! Complex numbers
c = cmplx(3.0, 4.0)
print *, "Complex: ", c
print *, "Real part: ", real(c)
print *, "Imaginary part: ", aimag(c)
! Character to integercharacter(len=10) :: str = "42"
read(str, *) i
print *, "String to integer: ", i
! Integer to character
i = 42write(str, *) i
print *, "Integer to string: ", trim(str)
endprogram type_conversion
Quick answerBinary Search is an efficient algorithm for finding elements in sorted arrays. It works by repeatedly dividing the search interval in half.
O(log n): Efficient search complexity
Sorted Array: Requires sorted input
Recursive/Iterative: Both implementations possible
Quick answerQuick Sort is a divide-and-conquer sorting algorithm that picks a pivot and partitions the array around it. It has O(n log n) average complexity.
Divide and Conquer: Recursive algorithm
Pivot Selection: Usually first, last, or middle element
Partitioning: Elements less than pivot go left
Recursive Sorting: Sort left and right partitions
In-place: Sorts array in-place
Fortran
! Quick Sort in Fortranmodule sorting
containsrecursivesubroutine quick_sort(arr, first, last)
integer, dimension(:), intent(inout) :: arr
integer, intent(in) :: first, last
integer :: pivot, i, j, temp
if (first < last) then
pivot = arr((first + last) / 2)
i = first
j = last
dodowhile (arr(i) < pivot)
i = i + 1enddodowhile (arr(j) > pivot)
j = j - 1enddoif (i >= j) exit
temp = arr(i)
arr(i) = arr(j)
arr(j) = temp
i = i + 1
j = j - 1enddocall quick_sort(arr, first, j)
call quick_sort(arr, i, last)
endifendsubroutine quick_sort
endmodule sorting
program test_quick_sort
use sorting
implicitnoneinteger, dimension(10) :: arr = [64, 34, 25, 12, 22, 11, 90, 1, 55, 47]
print *, "Before sorting: ", arr
call quick_sort(arr, 1, size(arr))
print *, "After sorting: ", arr
endprogram test_quick_sort
Quick answerMerge Sort is a divide-and-conquer algorithm that divides the array into halves, recursively sorts them, and merges the results. It has O(n log n) time complexity.
Divide: Split array into two halves
Recursive Sort: Sort each half
Merge: Combine sorted halves
Stable: Maintains relative order
O(n log n): Guaranteed performance
Fortran
! Merge Sort in Fortranmodule merge_sort
containsrecursivesubroutine merge_sort(arr, temp, left, right)
integer, dimension(:), intent(inout) :: arr, temp
integer, intent(in) :: left, right
integer :: mid
if (left < right) then
mid = (left + right) / 2call merge_sort(arr, temp, left, mid)
call merge_sort(arr, temp, mid + 1, right)
callmerge(arr, temp, left, mid, right)
endifendsubroutine merge_sort
subroutinemerge(arr, temp, left, mid, right)
integer, dimension(:), intent(inout) :: arr, temp
integer, intent(in) :: left, mid, right
integer :: i, j, k
i = left
j = mid + 1
k = left
dowhile (i <= mid .and. j <= right)
if (arr(i) <= arr(j)) then
temp(k) = arr(i)
i = i + 1else
temp(k) = arr(j)
j = j + 1endif
k = k + 1enddodowhile (i <= mid)
temp(k) = arr(i)
i = i + 1
k = k + 1enddodowhile (j <= right)
temp(k) = arr(j)
j = j + 1
k = k + 1enddo
arr(left:right) = temp(left:right)
endsubroutinemergeendmodule merge_sort
program test_merge_sort
use merge_sort
implicitnoneinteger, dimension(8) :: arr = [38, 27, 43, 3, 9, 82, 10, 7]
integer, dimension(8) :: temp
print *, "Before sorting: ", arr
call merge_sort(arr, temp, 1, size(arr))
print *, "After sorting: ", arr
endprogram test_merge_sort
Quick answerBubble Sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order.
O(n²): Average and worst-case complexity
Stable: Maintains relative order of equal elements
Quick answerNumerical Integration computes the definite integral of a function using methods like trapezoidal rule and Simpson's rule.
Trapezoidal Rule: TRAPEZOIDAL function
Simpson's Rule: SIMPSON function
Adaptive Methods: Adjust step size dynamically
Monte Carlo: Random sampling integration
Gauss Quadrature: Higher accuracy
Fortran
! Numerical Integration (Trapezoidal Rule)module integration
containsfunction trapezoidal(f, a, b, n) result(integral)
interfacefunction f(x) result(y)
real, intent(in) :: x
real :: y
endfunction f
endinterfacereal, intent(in) :: a, b
integer, intent(in) :: n
real :: integral
real :: h, x
integer :: i
h = (b - a) / n
integral = (f(a) + f(b)) / 2.0do i = 1, n - 1
x = a + i * h
integral = integral + f(x)
enddo
integral = integral * h
endfunction trapezoidal
function simpson(f, a, b, n) result(integral)
interfacefunction f(x) result(y)
real, intent(in) :: x
real :: y
endfunction f
endinterfacereal, intent(in) :: a, b
integer, intent(in) :: n
real :: integral
real :: h, x
integer :: i
h = (b - a) / n
integral = f(a) + f(b)
do i = 1, n - 1
x = a + i * h
if (mod(i, 2) == 0) then
integral = integral + 2.0 * f(x)
else
integral = integral + 4.0 * f(x)
endifenddo
integral = integral * h / 3.0endfunction simpson
endmodule integration
program test_integration
use integration
implicitnoneprint *, "Trapezoidal: ", trapezoidal(f, 0.0, 1.0, 1000)
print *, "Simpson: ", simpson(f, 0.0, 1.0, 1000)
containsfunction f(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
endfunction f
endprogram test_integration
Quick answerNewton's Method is an iterative root-finding algorithm that uses the derivative to find successively better approximations to the roots of a function.
Iterative: Repeated approximations
Derivative: Requires derivative of function
Convergence: Quadratic convergence
Initial Guess: Must be close to root
Implementation: NEWTON subroutine
Fortran
! Newton's Methodmodule numerical
containssubroutine newton(f, df, x0, tolerance, max_iter, result)
interfacefunction f(x) result(y)
real, intent(in) :: x
real :: y
endfunction f
function df(x) result(y)
real, intent(in) :: x
real :: y
endfunction df
endinterfacereal, intent(in) :: x0, tolerance
integer, intent(in) :: max_iter
real, intent(out) :: result
real :: x, fx, dfx
integer :: i
x = x0
do i = 1, max_iter
fx = f(x)
dfx = df(x)
if (abs(dfx) < 1.0e-10) then
result = x
returnendif
x = x - fx / dfx
if (abs(fx) < tolerance) then
result = x
returnendifenddo
result = x
endsubroutine newton
endmodule numerical
program test_newton
use numerical
implicitnonereal :: result
call newton(f, df, 1.0, 1.0e-6, 100, result)
print *, "Newton's method result: ", result
containsfunction f(x) result(y)
real, intent(in) :: x
real :: y
y = x * x - 2.0endfunction f
function df(x) result(y)
real, intent(in) :: x
real :: y
y = 2.0 * x
endfunction df
endprogram test_newton
Quick answerGaussian Elimination is a method for solving systems of linear equations. It transforms the system into an upper triangular form and then back-substitutes.
Forward Elimination: Transform to upper triangular
Back Substitution: Solve for variables
Pivoting: Avoid division by zero
Matrix Form: Ax = b
Implementation: GAUSSIAN_ELIMINATION
Fortran
! Linear Algebra - Gaussian Eliminationmodule linear_algebra
containssubroutine gaussian_elimination(a, b, x)
real, dimension(:,:), intent(inout) :: a
real, dimension(:), intent(inout) :: b
real, dimension(:), intent(out) :: x
integer :: n, i, j, k
real :: factor, sum
n = size(a, 1)
! Forward eliminationdo k = 1, n - 1do i = k + 1, n
factor = a(i, k) / a(k, k)
a(i, k:n) = a(i, k:n) - factor * a(k, k:n)
b(i) = b(i) - factor * b(k)
enddoenddo! Back substitution
x(n) = b(n) / a(n, n)
do i = n - 1, 1, -1sum = b(i)
do j = i + 1, n
sum = sum - a(i, j) * x(j)
enddo
x(i) = sum / a(i, i)
enddoendsubroutine gaussian_elimination
endmodule linear_algebra
program test_gaussian
use linear_algebra
implicitnonereal, dimension(3,3) :: a
real, dimension(3) :: b, x
a = reshape([2.0, -1.0, 0.0, -1.0, 2.0, -1.0, 0.0, -1.0, 2.0], [3, 3])
b = [1.0, 0.0, 1.0]
call gaussian_elimination(a, b, x)
print *, "Solution: ", x
endprogram test_gaussian
Quick answerCoarrays are Fortran's native parallel programming feature introduced in Fortran 2008. They enable SPMD (Single Program Multiple Data) parallelism.
Declaration: INTEGER, DIMENSION(n)[*] :: arr
Access: arr(i)[image]
Synchronization: SYNC ALL
Images: THIS_IMAGE() and NUM_IMAGES()
Collective Operations: CO_SUM, CO_MAX, CO_MIN
Fortran
! Coarray Programmingprogram coarray_example
implicitnoneinteger, dimension(10)[*] :: coarray
integer :: i, me
me = this_image()
! Initializedo i = 1, 10
coarray(i)[me] = i * me
enddosyncall! Access from other imagesif (me == 1) thendo i = 2, num_images()
print *, "Image ", i, " coarray(1): ", coarray(1)[i]
enddoendifsyncallendprogram coarray_example
Quick answerNamed Common Blocks are a legacy Fortran feature for sharing data between program units. They are still used in older code but are discouraged in favor of modules.
Declaration: COMMON /block_name/ var1, var2
Use: COMMON /block_name/ var1, var2
Module Alternative: Use modules for better encapsulation
Global Data: Shared across program units
Maintenance: Harder to maintain than modules
Fortran
! Named Common Blocksmodule common_blocks
integer :: x, y
common /block1/ x, y
endmodule common_blocks
program test_common
use common_blocks
implicitnone
x = 10
y = 20print *, "x = ", x, " y = ", y
call modify_values()
print *, "After modify: x = ", x, " y = ", y
containssubroutine modify_values()
integer :: x, y
common /block1/ x, y
x = 100
y = 200endsubroutine modify_values
endprogram test_common
Quick answerPointer Arrays allow flexible array manipulation by creating references to array data. They can point to array sections and be associated with different targets.
Declaration: INTEGER, POINTER, DIMENSION(:) :: p
Association: p => arr
Pointer to Section: p => arr(2:4)
Nullify: NULLIFY(p)
Allocatable: ALLOCATE(p(n))
Fortran
! Pointer Arraysprogram pointer_arrays
implicitnoneinteger, pointer :: p(:)
integer, target :: arr(5) = [1, 2, 3, 4, 5]
integer :: i
p => arr
print *, "p points to arr: ", p
p = p * 2print *, "After p = p * 2: ", arr
! Pointer to array section
p => arr(2:4)
print *, "p points to arr(2:4): ", p
! Nullify pointernullify(p)
endprogram pointer_arrays
How interviewers ask it“How would you explain derived types with allocatable components to a junior engineer, and what do people most often get wrong?”
Quick answerAbstract Interfaces define a procedure signature without an implementation. They are used with procedure pointers and type-bound procedures.
Definition: ABSTRACT INTERFACE
Procedure Pointer: PROCEDURE(func_interface), POINTER :: f
Type-bound: PROCEDURE(func_interface), POINTER :: f
Use: PROCEDURE(func_interface), POINTER :: f
Deferred Binding: Use with abstract types
Fortran
! Abstract Interfacesmodule abstract_interface
implicitnone! Abstract interfaceabstractinterfacefunction func_interface(x) result(y)
real, intent(in) :: x
real :: y
endfunction func_interface
endinterfacetype :: Integrator
procedure(func_interface), pointer, nopass :: f
containsprocedure :: integrate
endtype Integrator
containsfunction integrate(self, a, b, n) result(integral)
class(Integrator), intent(in) :: self
real, intent(in) :: a, b
integer, intent(in) :: n
real :: integral
real :: h, x
integer :: i
h = (b - a) / n
integral = (self%f(a) + self%f(b)) / 2.0do i = 1, n - 1
x = a + i * h
integral = integral + self%f(x)
enddo
integral = integral * h
endfunction integrate
endmodule abstract_interface
module functions
implicitnonecontainsfunction square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
endfunction square
function cube(x) result(y)
real, intent(in) :: x
real :: y
y = x * x * x
endfunction cube
endmodule functions
program test_abstract
use abstract_interface
use functions
implicitnonetype(Integrator) :: integrator
integrator%f => square
print *, "Square integral: ", integrator%integrate(0.0, 1.0, 1000)
integrator%f => cube
print *, "Cube integral: ", integrator%integrate(0.0, 1.0, 1000)
endprogram test_abstract
Quick answerProcedural Pointers are variables that point to procedures. They enable dynamic procedure calls and callback mechanisms.
Interface: Define interface for procedure
Pointer: PROCEDURE(func_proc), POINTER :: fp
Assignment: fp => square
Call: result = fp(5.0)
Use Cases: Generic algorithms, callbacks
Fortran
! Procedural Pointersprogram procedural_pointers
implicitnone! Define procedure pointer typeinterfacefunction func_proc(x) result(y)
real, intent(in) :: x
real :: y
endfunction func_proc
endinterfaceprocedure(func_proc), pointer :: fp
real :: result
fp => square
result = fp(5.0)
print *, "Square of 5: ", result
fp => cube
result = fp(5.0)
print *, "Cube of 5: ", result
containsfunction square(x) result(y)
real, intent(in) :: x
real :: y
y = x * x
endfunction square
function cube(x) result(y)
real, intent(in) :: x
real :: y
y = x * x * x
endfunction cube
endprogram procedural_pointers
Quick answerRandom Number Generator uses RANDOM_NUMBER and RANDOM_SEED to generate pseudo-random numbers with various distributions.
Initialize: CALL RANDOM_SEED
Uniform: CALL RANDOM_NUMBER(x)
Normal Distribution: Box-Muller transform
Reproducible: Set seed for reproducibility
Array Generation: Generate arrays of random numbers
Fortran
! Random Number Generatormodule random_generator
implicitnoneinteger :: seed = 12345containssubroutine init_random_seed()
integer :: i, n, clock
integer, dimension(:), allocatable :: seed_array
callrandom_seed(size=n)
allocate(seed_array(n))
callsystem_clock(count=clock)
seed_array = clock + 37 * [(i, i = 1, n)]
callrandom_seed(put=seed_array)
deallocate(seed_array)
endsubroutine init_random_seed
function random_uniform() result(x)
real :: x
callrandom_number(x)
endfunction random_uniform
function random_normal() result(x)
real :: x, y, z
real :: u1, u2
callrandom_number(u1)
callrandom_number(u2)
x = sqrt(-2.0 * log(u1)) * cos(2.0 * 3.14159 * u2)
endfunction random_normal
endmodule random_generator
program test_random
use random_generator
implicitnoneinteger :: i
call init_random_seed()
print *, "Uniform random numbers:"do i = 1, 5print *, random_uniform()
enddoprint *, "Normal random numbers:"do i = 1, 5print *, random_normal()
enddoendprogram test_random
Quick answerB-Tree is a balanced tree data structure that maintains sorted data and allows searches, sequential access, insertions, and deletions in logarithmic time.
Node: Contains keys and children pointers
Degree: Minimum degree of the tree
Insert: Insert with split
Search: Efficient search
Use Cases: Databases, file systems
Fortran
! B-Tree Implementationmodule btree
implicitnoneinteger, parameter :: T = 2! Minimum degreetype :: BTreeNode
integer :: n = 0logical :: leaf = .true.integer, dimension(2*T-1) :: keys
type(BTreeNode), pointer, dimension(2*T) :: children => null()
endtype BTreeNode
type :: BTree
type(BTreeNode), pointer :: root => null()
containsprocedure :: insert
procedure :: search
procedure :: inorder
procedure :: destroy
endtype BTree
containssubroutine split_child(self, node, i)
class(BTree), intent(inout) :: self
type(BTreeNode), pointer, intent(inout) :: node
integer, intent(in) :: i
type(BTreeNode), pointer :: y, z
y => node%children(i)
allocate(z)
z%leaf = y%leaf
z%n = T - 1! Copy keys to z
z%keys(1:T-1) = y%keys(T+1:2*T-1)
! Copy children if not leafif (.not. y%leaf) thenallocate(z%children(2*T))
z%children(1:T) = y%children(T+1:2*T)
endif
y%n = T - 1! Shift children in nodedo j = node%n + 1, i + 1, -1
node%children(j+1) => node%children(j)
enddo
node%children(i+1) => z
! Shift keys in nodedo j = node%n, i, -1
node%keys(j+1) = node%keys(j)
enddo
node%keys(i) = y%keys(T)
node%n = node%n + 1endsubroutine split_child
subroutine insert_non_full(self, node, key)
class(BTree), intent(inout) :: self
type(BTreeNode), pointer, intent(inout) :: node
integer, intent(in) :: key
integer :: i
if (node%leaf) then
i = node%n
dowhile (i >= 1.and. key < node%keys(i))
node%keys(i+1) = node%keys(i)
i = i - 1enddo
node%keys(i+1) = key
node%n = node%n + 1else
i = node%n
dowhile (i >= 1.and. key < node%keys(i))
i = i - 1enddo
i = i + 1if (node%children(i)%n == 2*T - 1) thencall split_child(self, node, i)
if (key > node%keys(i)) then
i = i + 1endifendifcall insert_non_full(self, node%children(i), key)
endifendsubroutine insert_non_full
subroutine insert(self, key)
class(BTree), intent(inout) :: self
integer, intent(in) :: key
type(BTreeNode), pointer :: new_root
if (.not.associated(self%root)) thenallocate(self%root)
self%root%leaf = .true.
self%root%n = 0allocate(self%root%children(2*T))
endifif (self%root%n == 2*T - 1) thenallocate(new_root)
new_root%leaf = .false.
new_root%n = 0allocate(new_root%children(2*T))
new_root%children(1) => self%root
call split_child(self, new_root, 1)
self%root => new_root
endifcall insert_non_full(self, self%root, key)
endsubroutine insert
recursivefunction search(self, node, key) result(found)
class(BTree), intent(in) :: self
type(BTreeNode), pointer, intent(in) :: node
integer, intent(in) :: key
logical :: found
integer :: i
if (.not.associated(node)) then
found = .false.returnendif
i = 1dowhile (i <= node%n .and. key > node%keys(i))
i = i + 1enddoif (i <= node%n .and. key == node%keys(i)) then
found = .true.elseif (node%leaf) then
found = .false.else
found = self%search(node%children(i), key)
endifendfunction search
recursivesubroutine inorder(self, node)
class(BTree), intent(in) :: self
type(BTreeNode), pointer, intent(in) :: node
integer :: i
if (associated(node)) thendo i = 1, node%n
call self%inorder(node%children(i))
print *, node%keys(i)
enddocall self%inorder(node%children(node%n + 1))
endifendsubroutine inorder
recursivesubroutine destroy(self, node)
class(BTree), intent(inout) :: self
type(BTreeNode), pointer, intent(inout) :: node
integer :: i
if (associated(node)) thendo i = 1, node%n + 1call self%destroy(node%children(i))
enddoif (associated(node%children)) deallocate(node%children)
deallocate(node)
endifendsubroutine destroy
endmodule btree
program test_btree
use btree
implicitnonetype(BTree) :: tree
call tree%insert(10)
call tree%insert(20)
call tree%insert(30)
call tree%insert(40)
call tree%insert(50)
call tree%insert(60)
call tree%insert(70)
call tree%insert(80)
call tree%insert(90)
print *, "B-Tree Inorder:"call tree%inorder(tree%root)
print *, "Search 40: ", tree%search(tree%root, 40)
print *, "Search 100: ", tree%search(tree%root, 100)
call tree%destroy(tree%root)
endprogram test_btree
Quick answerGraph Adjacency List is a graph representation where each vertex maintains a list of its neighbors. It's more memory efficient for sparse graphs.
Vertices: List of vertices
Edges: Each vertex has a list of neighbors
Weighted: Store weights along with edges
BFS/DFS: Graph traversal algorithms
Memory: O(V + E) memory
Fortran
! Graph Adjacency Listmodule graph_adj_list
implicitnonetype :: Edge
integer :: dest
integer :: weight
type(Edge), pointer :: next => null()
endtype Edge
type :: Graph
integer :: vertices
type(Edge), pointer, dimension(:), allocatable :: adj_list
containsprocedure :: init
procedure :: add_edge
procedure :: print_graph
procedure :: dfs
procedure :: bfs
endtype Graph
containssubroutine init(self, v)
class(Graph), intent(inout) :: self
integer, intent(in) :: v
self%vertices = v
allocate(self%adj_list(v))
nullify(self%adj_list)
endsubroutine init
subroutine add_edge(self, u, v, w)
class(Graph), intent(inout) :: self
integer, intent(in) :: u, v, w
type(Edge), pointer :: new_edge
allocate(new_edge)
new_edge%dest = v
new_edge%weight = w
new_edge%next => self%adj_list(u)
self%adj_list(u) => new_edge
! For undirected graphallocate(new_edge)
new_edge%dest = u
new_edge%weight = w
new_edge%next => self%adj_list(v)
self%adj_list(v) => new_edge
endsubroutine add_edge
subroutine print_graph(self)
class(Graph), intent(in) :: self
type(Edge), pointer :: current
integer :: i
do i = 1, self%vertices
print *, "Vertex ", i, ":"
current => self%adj_list(i)
dowhile (associated(current))
print *, " -> ", current%dest, " (weight: ", current%weight, ")"
current => current%next
enddoenddoendsubroutine print_graph
recursivesubroutine dfs_recursive(self, v, visited)
class(Graph), intent(in) :: self
integer, intent(in) :: v
logical, dimension(:), intent(inout) :: visited
type(Edge), pointer :: current
visited(v) = .true.print *, "Visited: ", v
current => self%adj_list(v)
dowhile (associated(current))
if (.not. visited(current%dest)) thencall self%dfs_recursive(current%dest, visited)
endif
current => current%next
enddoendsubroutine dfs_recursive
subroutine dfs(self, start)
class(Graph), intent(in) :: self
integer, intent(in) :: start
logical, dimension(:), allocatable :: visited
allocate(visited(self%vertices))
visited = .false.call self%dfs_recursive(start, visited)
deallocate(visited)
endsubroutine dfs
subroutine bfs(self, start)
class(Graph), intent(in) :: self
integer, intent(in) :: start
logical, dimension(:), allocatable :: visited
integer, dimension(:), allocatable :: queue
integer :: front, rear, v
type(Edge), pointer :: current
allocate(visited(self%vertices))
allocate(queue(self%vertices))
visited = .false.
front = 1
rear = 1
visited(start) = .true.
queue(rear) = start
rear = rear + 1dowhile (front < rear)
v = queue(front)
front = front + 1print *, "Visited: ", v
current => self%adj_list(v)
dowhile (associated(current))
if (.not. visited(current%dest)) then
visited(current%dest) = .true.
queue(rear) = current%dest
rear = rear + 1endif
current => current%next
enddoenddodeallocate(visited, queue)
endsubroutine bfs
endmodule graph_adj_list
program test_graph_adj
use graph_adj_list
implicitnonetype(Graph) :: g
call g%init(6)
call g%add_edge(1, 2, 10)
call g%add_edge(1, 3, 5)
call g%add_edge(2, 4, 2)
call g%add_edge(3, 5, 4)
call g%add_edge(4, 6, 9)
call g%add_edge(5, 6, 3)
call g%print_graph()
print *, "DFS from 1:"call g%dfs(1)
print *, "BFS from 1:"call g%bfs(1)
endprogram test_graph_adj
Quick answerLongest Common Subsequence (LCS) finds the longest subsequence common to two sequences. It uses dynamic programming.
DP Table: Stores LCS lengths
Recurrence: Match or skip characters
Time Complexity: O(mn)
Path Reconstruction: Can reconstruct the LCS
Use Cases: Bioinformatics, text comparison
Fortran
! Longest Common Subsequencemodule lcs
containsfunction lcs_length(a, b) result(length)
character(len=*), intent(in) :: a, b
integer :: length
integer :: m, n, i, j
integer, dimension(:,:), allocatable :: dp
m = len(a)
n = len(b)
allocate(dp(m+1, n+1))
dp = 0do i = 1, m
do j = 1, n
if (a(i:i) == b(j:j)) then
dp(i+1, j+1) = dp(i, j) + 1else
dp(i+1, j+1) = max(dp(i, j+1), dp(i+1, j))
endifenddoenddo
length = dp(m+1, n+1)
deallocate(dp)
endfunction lcs_length
endmodule lcs
program test_lcs
use lcs
implicitnonecharacter(len=20) :: a = "ABCBDAB"character(len=20) :: b = "BDCAB"print *, "LCS Length: ", lcs_length(a, b)
endprogram test_lcs
Quick answerEdit Distance (Levenshtein distance) measures the minimum number of edits (insertions, deletions, substitutions) to transform one string into another.
DP Table: Stores edit distances
Operations: Insert, Delete, Substitute
Time Complexity: O(mn)
Use Cases: Spell checking, DNA sequence alignment
Fortran
! Edit Distancemodule edit_distance
containsfunction edit_distance(a, b) result(distance)
character(len=*), intent(in) :: a, b
integer :: distance
integer :: m, n, i, j
integer, dimension(:,:), allocatable :: dp
m = len(a)
n = len(b)
allocate(dp(m+1, n+1))
do i = 1, m+1
dp(i, 1) = i - 1enddodo j = 1, n+1
dp(1, j) = j - 1enddodo i = 2, m+1do j = 2, n+1if (a(i-1:i-1) == b(j-1:j-1)) then
dp(i, j) = dp(i-1, j-1)
else
dp(i, j) = 1 + min(dp(i-1, j), dp(i, j-1), dp(i-1, j-1))
endifenddoenddo
distance = dp(m+1, n+1)
deallocate(dp)
endfunction edit_distance
endmodule edit_distance
program test_edit_distance
use edit_distance
implicitnonecharacter(len=20) :: a = "kitten"character(len=20) :: b = "sitting"print *, "Edit distance: ", edit_distance(a, b)
endprogram test_edit_distance
Quick answerTrie (Prefix Tree) is a tree-like data structure for efficient string storage and retrieval. It supports prefix search and auto-completion.
Node: Children array and end marker
Insert: Add word
Search: Exact word search
StartsWith: Prefix search
Use Cases: Autocomplete, dictionary
Fortran
! Trie Data Structuremodule trie
implicitnoneinteger, parameter :: ALPHABET_SIZE = 26type :: TrieNode
logical :: is_end = .false.type(TrieNode), pointer :: children(ALPHABET_SIZE) => null()
endtype TrieNode
type :: Trie
type(TrieNode), pointer :: root => null()
containsprocedure :: init
procedure :: insert
procedure :: search
procedure :: starts_with
endtype Trie
containssubroutine init(self)
class(Trie), intent(inout) :: self
allocate(self%root)
self%root%is_end = .false.endsubroutine init
subroutine insert(self, word)
class(Trie), intent(inout) :: self
character(len=*), intent(in) :: word
type(TrieNode), pointer :: current
integer :: i, idx
current => self%root
do i = 1, len(word)
idx = iachar(word(i:i)) - iachar('a') + 1if (.not.associated(current%children(idx))) thenallocate(current%children(idx))
current%children(idx)%is_end = .false.endif
current => current%children(idx)
enddo
current%is_end = .true.endsubroutine insert
function search(self, word) result(found)
class(Trie), intent(in) :: self
character(len=*), intent(in) :: word
logical :: found
type(TrieNode), pointer :: current
integer :: i, idx
current => self%root
do i = 1, len(word)
idx = iachar(word(i:i)) - iachar('a') + 1if (.not.associated(current%children(idx))) then
found = .false.returnendif
current => current%children(idx)
enddo
found = current%is_end
endfunction search
function starts_with(self, prefix) result(found)
class(Trie), intent(in) :: self
character(len=*), intent(in) :: prefix
logical :: found
type(TrieNode), pointer :: current
integer :: i, idx
current => self%root
do i = 1, len(prefix)
idx = iachar(prefix(i:i)) - iachar('a') + 1if (.not.associated(current%children(idx))) then
found = .false.returnendif
current => current%children(idx)
enddo
found = .true.endfunction starts_with
endmodule trie
program test_trie
use trie
implicitnonetype(Trie) :: trie
call trie%init()
call trie%insert("apple")
call trie%insert("app")
call trie%insert("apply")
print *, "Search 'apple': ", trie%search("apple")
print *, "Search 'app': ", trie%search("app")
print *, "Search 'ap': ", trie%search("ap")
print *, "Starts with 'appl': ", trie%starts_with("appl")
print *, "Starts with 'xyz': ", trie%starts_with("xyz")
endprogram test_trie
Quick answerSuffix Array is an array of all suffixes of a string sorted lexicographically. It's used for string matching and compression.
Build: Sort suffixes
Search: Pattern searching
LCP: Longest Common Prefix
Time Complexity: O(n log n) build
Use Cases: String matching, data compression
Fortran
! Suffix Arraymodule suffix_array
containsfunction build_suffix_array(str) result(sa)
character(len=*), intent(in) :: str
integer, dimension(:), allocatable :: sa
integer :: n, i
n = len(str)
allocate(sa(n))
do i = 1, n
sa(i) = i
enddo! Simple implementation - sort suffixescall sort_suffixes(str, sa, 1, n)
endfunction build_suffix_array
recursivesubroutine sort_suffixes(str, sa, l, r)
character(len=*), intent(in) :: str
integer, dimension(:), intent(inout) :: sa
integer, intent(in) :: l, r
integer :: i, j, pivot
if (l < r) then
pivot = l
i = l
j = r
dowhile (i < j)
dowhile (compare_suffix(str, sa(i), sa(pivot)) <= 0.and. i < r)
i = i + 1enddodowhile (compare_suffix(str, sa(j), sa(pivot)) > 0)
j = j - 1enddoif (i < j) thencall swap(sa(i), sa(j))
endifenddocall swap(sa(pivot), sa(j))
call sort_suffixes(str, sa, l, j - 1)
call sort_suffixes(str, sa, j + 1, r)
endifendsubroutine sort_suffixes
function compare_suffix(str, i, j) result(cmp)
character(len=*), intent(in) :: str
integer, intent(in) :: i, j
integer :: cmp
integer :: k, n
n = len(str)
k = 0dowhile (i + k <= n .and. j + k <= n .and. str(i+k:i+k) == str(j+k:j+k))
k = k + 1enddoif (i + k > n .and. j + k > n) then
cmp = 0elseif (i + k > n) then
cmp = -1elseif (j + k > n) then
cmp = 1elseif (str(i+k:i+k) < str(j+k:j+k)) then
cmp = -1else
cmp = 1endifendfunction compare_suffix
subroutine swap(a, b)
integer, intent(inout) :: a, b
integer :: temp
temp = a
a = b
b = temp
endsubroutine swap
endmodule suffix_array
program test_suffix_array
use suffix_array
implicitnoneinteger, dimension(:), allocatable :: sa
character(len=20) :: str = "banana"integer :: i
sa = build_suffix_array(str)
print *, "Suffix array for 'banana':"do i = 1, size(sa)
print *, sa(i), " -> ", str(sa(i):)
enddoendprogram test_suffix_array
Quick answerTower of Hanoi is a classic problem of moving disks between three rods. It's solved with recursion and has 2^n - 1 moves.
Recursive: Move n-1 disks, move largest, move n-1
Moves: 2^n - 1 minimum moves
Rods: Source, destination, auxiliary
Use Cases: Recursion, algorithms
Fortran
! Tower of Hanoimodule hanoi
implicitnoneinteger :: moves = 0containsrecursivesubroutine solve_hanoi(n, from, to, aux)
integer, intent(in) :: n
character(len=1), intent(in) :: from, to, aux
if (n == 1) then
moves = moves + 1print *, moves, ": Move disk 1 from ", from, " to ", to
elsecall solve_hanoi(n - 1, from, aux, to)
moves = moves + 1print *, moves, ": Move disk ", n, " from ", from, " to ", to
call solve_hanoi(n - 1, aux, to, from)
endifendsubroutine solve_hanoi
endmodule hanoi
program test_hanoi
use hanoi
implicitnoneinteger :: n = 3print *, "Tower of Hanoi with ", n, " disks:"call solve_hanoi(n, 'A', 'C', 'B')
print *, "Total moves: ", moves
endprogram test_hanoi
Fortran is one of the oldest high-level programming languages, primarily used for scientific computing, numerical analysis, engineering simulations, and high-performance computing.
What are the main features of Modern Fortran?
Modern Fortran includes modules, derived types, array operations, dynamic memory allocation, pointers, recursion, object-oriented programming, and parallel programming support.
What are modules in Fortran?
Modules are reusable program units that contain variables, procedures, interfaces, and type definitions which can be shared across multiple programs.
What are derived types?
Derived types are user-defined data structures that group multiple related variables into a single type, similar to structures in C.
How are arrays used in Fortran?
Arrays are first-class objects in Fortran and support efficient numerical operations, slicing, whole-array assignments, and mathematical computations.
What is OpenMP in Fortran?
OpenMP is an API used for shared-memory parallel programming that enables multiple CPU cores to execute Fortran programs concurrently.
What is MPI in Fortran?
MPI (Message Passing Interface) is a communication standard used for distributed-memory parallel computing in scientific and engineering applications.
Where is Fortran commonly used?
Fortran is widely used in weather forecasting, aerospace, engineering simulations, computational physics, climate modeling, and high-performance scientific computing.
Why is Fortran still relevant today?
Fortran remains relevant because many scientific applications and high-performance computing systems rely on its efficient numerical computation capabilities and decades of optimized legacy code.
AK
Written and reviewed by Abhishek Kumar
Founder, InterviewPitch · 10+ years in IT. Questions are collected from real interview rounds and refreshed regularly. Spotted an error? Tell us.