In: Computer Science
java
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.
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 a product instead. And you’ll need to think about what should happen if the user enters 0.
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. You should not need to change any of the code that computes the factorial!
Code is Given Below:
==========================
import java.util.Scanner;
public class Factorials {
public static void main(String[] args) {
//creating Scanner object to get
input from user
Scanner scn=new
Scanner(System.in);
System.out.print("Enter
non-negative integer : ");
int n=scn.nextInt();
int fact=1,i=1;
//checking if number is 0
if(n==0) {
System.out.println("Factorial of "+n+" is "+fact);
return;
}
//finding factorial
while(i<=n) {
fact=fact*i;
i++;
}
//displaying result
System.out.println("Factorial of
"+n+" is "+fact);
}
}
Output:
=================
Code Snapshot:
=========================
Modified Code:- Handling Negative values
============================================
import java.util.Scanner;
public class Factorials {
public static void main(String[] args) {
//creating Scanner object to get
input from user
Scanner scn=new
Scanner(System.in);
System.out.print("Enter
non-negative integer : ");
int n=scn.nextInt();
//checking if number is
negative
while(n<0) {
System.out.print("Enter non-negative integer : ");
n=scn.nextInt();
}
int fact=1,i=1;
//checking if number is 0
if(n==0) {
System.out.println("Factorial of "+n+" is "+fact);
return;
}
//finding factorial
while(i<=n) {
fact=fact*i;
i++;
}
//displaying result
System.out.println("Factorial of
"+n+" is "+fact);
}
}
Output:
=============
Code Snapshot
=================