Java Reference
In-Depth Information
Recursive methods, although elegant, often show much worse perfor-
mance than those that use conventional iteration. The following program
calculates the factorial function with a while loop that contains a single
line of code.
// Java for Engineers
// Filename: Factorial
// Reference: Chapter 23
// Description:
//
Non-recursive calculation of factorial
// Requires:
//
Keyin class in current directory
import java.lang.*;
class Factorial
{
public static void main(String[] args)
{
int num;
int prod = 1;
int factor = 1;
// Get user input
num = Keyin.inInt(“Enter factorial value: ”);
// Factorial calculation
while(factor <= num)
prod *= factor++;
System.out.println(“Factorial”+num+“is”+prod);
}
}
On the Web
The program Factorial.java is found in the Chapter 24 folder at
Evaluating Numeric Results
Java code can perform operations on numbers that produce unexpected,
unacceptable, or invalid results. For example, a program can accidentally
or unintentionally perform integer division by zero, which ends with Java
abruptly throwing an arithmetic exception, because division by zero is
mathematically undefined and thus is considered a logic error.