Java Reference
In-Depth Information
talking about a program loop that repeats a group of statements three
times, we speak of the first, the second, and the third iteration.
Programmers note:
The concept of program iteration is not limited to loop structures.
The word “iteration” describes any form of repetitive processing, in-
dependently of the logical means by which it is performed.
Elements of a program loop
A loop always involves three steps:
1. Theinitializationstepisusedtoprimetheloopvariablestoaninitialstate.
2. Theprocessingstepperformstheprocessing.Thisistheportionofthecode
that is repeated during each iteration.
3. The testing step evaluates the variables or conditions that determine the
continuationoftheloop.Iftheyaremet,theloopcontinues.Ifnot,theloop
ends.
A loop structure can be used to calculate the factorial. The factorial is
the product of all the whole numbers that are equal to or less than the
number. For example, factorial 5 (written 5!) is
5!=5*4*3*2*1=120
In coding a routine to calculate the factorial you can use one variable
to hold the accumulated product and another one to hold the current fac-
tor. The first variable could be named facProd and the second one
curFactor. The loop to calculate facProd can be as follows:
1. Initialize the variable facProd to the number whose factorial is to be calcu-
lated and the variable curFactor to this number minus 1. For example: to
calculate 5! you make facProd = 5 and curFactor = 4.
2. DuringeachiterationcalculatethenewvalueoffacProdbymakingfacProd
= curFactor times facProd. Subtract one from curFactor.
3. If curFactor is greater than 1 repeat step 2, if not, terminate the loop.
Figure10-1 isaflowchartofthelogicusedinthefactorialcalculation
described above.
Search WWH ::




Custom Search