Factorials
Do this project in the lab.
The factorial of n (written n!) is the product of the integers
between 1 and n. Thus 4! = 1*2*3*4 = 24. By definition, 0! = 1. Factorial
is not defined for negative numbers.
-
Write
a program, Fact.java, that asks the user for a non-negative integer and
computes and prints the
factorial of that integer. You'll need a while loop to do most of the work --
this is a lot like computing a sum, but it's a product instead. And you'll
need to think about what should happen if the user enters 0.
- Don't start writing code right away. Think first! Get out a paper and pencil (or a text editor), and write out a pseudo-code for your proposed solution. Call an instructor to look at your pseudo-code before beginning to write your code. You must do this to obtain extra credit.
- Okay, now on to Eclipse: convert your pseudo-code into Java.
- Test your program with a couple of small numbers (3 and 7, say). Don't try numbers bigger than about 50 as the program will may terminate with an overflow.
-
Now modify your program so that it checks to see if the user entered a
negative number. If so, the program should print a message saying that
a nonnegative number is required and ask the user the enter another number.
The program should keep doing this until the user enters a nonnegative
number, after which it should compute the factorial of that number. Hint:
you will need another while loop before the loop that computes the
factorial (as you may have to prompt the user repeatedly until they enter a correct input). You should not need to change any of the code that computes
the factorial!
Submit Fact.java. Copy a sample session of running the program into the lab document.