go to previous page   go to home page   go to next page hear noise

Answer:

It will use a counting loop.


Flowchart of the Program

flowchart of factorial


One way to do this is to use N as the counter, and count it down through the values 5, 4, 3, and 2. These values are multiplied together one by one. There is no need to multiply by 1, so the counting loop's condition is N > 1.

The flowchart shows how the program works. First it tests if N is positive or zero. If so, it calculates N!

N! is calculated by first initializing Fact to 1. Next, a counting loop multipilies Fact by N, then by N-1, then by N-2, and so on down to 2.

If N starts out at 0 or at 1, then the correct value of Fact is its initial value of one. The loop body will not execute even once.

This program uses somewhat trickier logic than previous programs. Study the flowchart until you see how it works. Don't worry about the details of Java right now. The flowchart is a logic design for the program. It would work for any language.


QUESTION 9:

Mentally go though the chart for some values of N. Does it work correctly for :

N == -5 
N ==  0
N ==  1
N ==  4?