10. Write a program that reads an integer from the keyboard and prints the factorial of the input. Use a variable of type long to store the result.
In mathematics, the factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example,
5! = 5 * 4 * 3 * 2 * 1 = 120.
import java.util.*;
public class Arithmetic {
public static void main(String[] args) {
int input;// stores user input
int i;// stores interation
Scanner keyboard = new Scanner(System.in);
do {
System.out.print("Enter a positive number: ");// prompt user
input = keyboard.nextInt();
} while (input < 0);// won't continue until a positive number is entered
long factorial = input;
for (i = input - 1; i >= 2; i--) {// loops through from one less than
// the input down to 2.
factorial = factorial * i;// multiple itself to the next interation
}
if (input == 0 || input == 1)// if the input is 0 or 1
factorial = 1;// the factorial is 1
System.out.println(input + "! = " + factorial);// print the result
keyboard.close();
}
}
No comments:
Post a Comment