Write a Java program that accepts a positive long integer between 2 to 15, and t
ID: 3575603 • Letter: W
Question
Write a Java program that accepts a positive long integer between 2 to 15, and then using the number, calculate its factorial (n!). Using do-while statement, make sure it only accepts a valid number (between 2 and 15) – if an invalid number is entered, program should display the original instruction again, using while loop. You can submit the source code only - .java file. Hint: all variables should be declared as long. Hint: After do-while loop for input validation, use for-loop to get the factorial *** Sample output Enter a number between 2 and 15: 15 Factorial of 15 is 1307674368000
Explanation / Answer
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
System.out.println("Enter a number between 2 and 15 (both inclusive) : ");
Scanner scanner = new Scanner(System.in);
Integer number = scanner.nextInt();
while (number > 15 || number < 2){
System.out.println("Enter a number between 2 and 15 (both inclusive) : ");
number = scanner.nextInt();
}
long factorial=1;
for(int i=2;i<=number;i++){
factorial *= i;
}
System.out.println("Factorial of "+number+ " : "+factorial);
}
}
==========================
output
===========================
Enter a number between 2 and 15 (both inclusive) : 16
Enter a number between 2 and 15 (both inclusive) : 0
Enter a number between 2 and 15 (both inclusive) : 1
Enter a number between 2 and 15 (both inclusive) : 15
Factorial of 15 : 1307674368000
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.