Provide the Java code that would be used find the factorial of a number using iteration and not recursion – in other words use a loop to find the factorial of a number.

Earlier we had discussed how to find the factorial of a number using recursion. Now, if we want to find the factorial of a number using iteration instead of recursion, how would we do that? It’s actually pretty simple, and it’s something you should try to figure out on your own.

A factorial of a number x is defined as the product of x and all positive integers below x. To calculate the factorial in a for loop, it seems like all we would have to do is start from x and then multiply by all integer values below x, and just hold that value until we are done iterating. And that is exactly what needs to be done. Here is what the code will look like in Java:

Java code for Iterative Factorial

int factorial ( int input )
{
  int x, fact = 1;
  for ( x = input; x > 1; x--)
     fact *= x;
     
  return fact;

}

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.