2. The factorial of a positive integer n is the product of the integers from 1 to n. You can express the factorial of a positive integer n (in mathematics this is denoted by n!) using the following formula: n! = 1 * 2 * 3 * ... * (n - 1) * n Write a Java program that will compute the factorial of some numbers n (input from the user, accept only range 1 - 10). For each valid number in input, the output should be the value of n!. Your program should use a loop, to allow the user to input more than one number (count-controlled or sentinel-controlled, your choice)

Respuesta :

Answer:

import java.io.*;

import java.util.Scanner;//importing the scanner.

class Factorial {

public static void main (String[] args) {

    Scanner fact=new Scanner(System.in);//creating a scanner object for taking the input.

    int t,n;//t for number of times the user want to calculate the factorial and n for factorial.

    System.out.println("How many times you want to calculate the factorial");

    t=fact.nextInt();//taking input of t.

    while(t>0)

    {

        int f=1;//f for calculating the variable.

        n=fact.nextInt();//taking input of n .

        if(n>10||n<1)//if n is out of range then again taking input.

        {

           while(n>10 || n<1)

                {

                        System.out.println("Please Enter the Valid Input");

                 n=fact.nextInt();

                }

               for(int i=1;i<=n;i++)//calculating the factorial.

               {

                   f*=i;

               }

               System.out.println("The factorial is: "+ f);

        }

        else // if n is in  range then definitely calculating the factorial.

        {

             for(int i=1;i<=n;i++)// calculating the factorial.

               {

                   f*=i;

               }

               System.out.println("The factorial is: "+ f);

        }

    }

}

}

Output:-

How many times you want to calculate the factorial

2

-5

Please Enter the Valid Input

4

The factorial is: 24

5

The factorial is: 120

Explanation:

The above written code is for calculating the factorial of an integer the number of times user want to calculate the factorial.The code wants user to enter again until the value entered by the user is in range.If the value is in range then it definitely calculates the factorial.