Java Reference
In-Depth Information
Compound statement in loops
You have learned that the roster symbols ({ and }) are used in Java to group
several statements into a single block. Statement blocks are used in loop
constructs to make possible performing more than one processing opera-
tion. The following program, named Factorial.java, uses a statement block
inaforlooptodisplaythepartialproductduringthefactorialcalculation.
On the Web
The program Factorial.java is found in the Chapter 10 folder at
www.crcpress.com .
//
File name: Factorial.java
//
Reference: Chapter 10
//
//
Java program to demonstrate looping
//
Topics:
//
1. Using the for loop
//
2. Loop with multiple processing statements
//
//
Requires:
//
1. Keyin class in the current directory
public class Factorial
{
public static void main(String[] args)
{
int number;
int facProd;
int curFactor;
System.out.println("FACTORIAL CALCULATION PROGRAM");
number = Keyin.inInt("Enter a positive integer: ");
facProd = number;
// Initializing
for(curFactor = number - 1; curFactor > 1; curFactor—)
{
facProd = curFactor * facProd;
System.out.println("Partial product: " + facProd);
System.out.println("Current factor: " + curFactor);
}
// Display the factorial
System.out.println("\n\nFactorial is: " + facProd);
}
}
Search WWH ::




Custom Search