Write a Java program that accepts a positive long integer between 2 to 15, and t
ID: 3695130 • 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. 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 between number 2 and 15: 15 Factorial of 15 is 1307674368000
Explanation / Answer
import java.util.*;
class longFact
{
public static void main(String args[])
{
long i,f=1,n;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("Enter number [2 - 15] ");
n=scan.nextLong();
if(n>=2 && n<=15)
break;
}while(true);
for(i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("Factorial of "+n+" is "+f);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.