FACTORIALS: The factorial of n (written n!) is the product of the integers betwe
ID: 3621308 • Letter: F
Question
FACTORIALS: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.
1. Write a program 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 product instead. And you'll need to think about what should happen if the user enters 0.
2. Now modify the 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 to the enter another number. The program should print a message saying 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. You should not need to change any of the code that computes the factorial!
Explanation / Answer
Hope this helps. Please rate. :) import java.io.BufferedReader; import java.io.InputStreamReader; public class Factorials { public static void main(String[] args) { int n = 0; int fact = 1; BufferedReader bin = new BufferedReader( new InputStreamReader(System.in)); try { System.out.print("Enter a positive integer: "); n = Integer.parseInt(bin.readLine()); } catch (Exception e) { e.printStackTrace(); } while (n < 0) { System.out.println("A nonnegative number is required."); System.out.print("Try again: "); try { n = Integer.parseInt(bin.readLine()); } catch (Exception e) { e.printStackTrace(); } } fact = 1; for (int i = 1; iRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.