The small program below calculates the absolute and relative errors in the Stirling's approximation $$n! = \sqrt{2\pi n}\left(\frac{n}{e}\right)^n$$ For n = 1,2,...10.
Program StirlingTable implicit none
integer :: n, nf
real :: stirling, abs_error, pi, rel_error
pi = acos(-1.0) ! definition of the variable pi
nf = 1 ! starting value for n!
do n = 1, 10
nf = nf*n
stirling = sqrt(2.0*pi*n)*exp(-real(n))*((n)**n)
abs_error = abs(nf - stirling)
rel_error = abs_error/nf
write(*,*) n, nf, stirling, &
abs_error, rel_error
end do
read(*,*)
End Program StirlingTable
When compiling, the results give
Could anyone help me analyze the reasons behind why the absolute error increases and the relative error decreases with the increase in n, especially within the context of the code.
That is, which part of the code would be responsible for the overflow error.
Thank you

The problem is due to integer overflow in the computation of $n^n$. In the case of $n=10$ the computed result is $10^{10} \equiv 1410065408 \mod 2^{31}$, where $2^{31}$ corresponds to the largest positive number of type "integer" in Fortran. The problem is fixed by forcing the compiler to issue floating point instructions as demonstrated below
A new problem emerges as the calculation of $n!$ overflows at $n=13$ and the computed value of nf equals $13! \equiv 1932053504 \mod 2^{31}$.
It could be a worthwhile addition to the exercise to also compute the logarithm of $n!$ and the logarithm of Stirling's approximation using the addition formula $\log(ab) = \log(a) + \log(b)$ as this would circumvent the current range issues.