Iterative Implementation of Factorial

Classic programmed-learning exercises, refreshed for modern Java and presented in the current MrStyner.com portfolio style.

Modern Java noteThis archive has been refreshed for Java 25 LTS. Core language concepts remain useful, while outdated setup instructions and browser-era Java are labeled or replaced. Java 26 is the current feature release; Java 25 is used here as the stable teaching baseline.

Answer:

Yes. No matter what you are computing, if there is a recursive way to do it, then there is an iterative way to do it. And if there is an iterative way to do it, then there is a recursive way.

Iterative Implementation of Factorial

Here is the math-like definition of recursion (again):

factorial( 0 ) = 1
factorial( N ) = N * factorial( N-1 )

And here is an iterative implementation:

int factorial( int N )
{
  int product = 1;
  for ( int j=1; j<=N; j++ )
    product *= j;
  return product;
}

Of course, this version suffers from the same overflow problem as the recursive version. For any argument larger than 12 the product is too large to hold in an int and incorrect values will be returned to the caller.

QUESTION 8:

What does this version compute if given a parameter of -1?