Q. Write a java factorial Program that calculates tha factorial of a given positive integer ‘number’. The program should prompt the user to enter an integer , and then compute and display tha factorial of the number .

Java Factorial Program

				
					class FactorialExample{
 public static void main(String args[])
 {
  int i,fact=1;
  int number=5;  //It is the number to calculate factorial
  for(i=1;i<=number;i++){
      fact=fact*i;
  }
  System.out.println("Factorial of "+number+" is: "+fact);
 }
}
				
			

Out Put

java factorial

Employee Hierarchy:

				
					import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int num = scanner.nextInt();
        
        // Using iterative approach
        System.out.println("Factorial using iterative approach: " + factorialIterative(num));
        
        // Using recursive approach
        System.out.println("Factorial using recursive approach: " + factorialRecursive(num));
        
        scanner.close();
    }
    
    // Iterative approach
    public static int factorialIterative(int num) {
        int factorial = 1;
        for (int i = 1; i <= num; i++) {
            factorial *= i;
        }
        return factorial;
    }
    
    // Recursive approach
    public static int factorialRecursive(int num) {
        if (num == 0 || num == 1) {
            return 1;
        } else {
            return num * factorialRecursive(num - 1);
        }
    }
}

				
			

Factorial is a mathematical operation denoted by an exclamation mark (!) that is applied to a non-negative integer. The factorial of a non-negative integer ( n ) (denoted as ( n! )) is the product of all positive integers less than or equal to ( n ).

1. **Definition**: For a non-negative integer ( n ), the factorial ( n! ) is defined as:
[ n! = n \times (n-1) \times (n-2) \times \ldots \times 3 \times 2 times 1 ]

(n!=n×(n−1)×(n−2)×…×3×2×1)

2. **Example**: Let’s take an example, ( 5! ) (read as “five factorial”). It is calculated as:
[ 5! = 5 \times 4 \times 3 \times 2 \times 1 = 120 ]

(5!=5×4×3×2×1=120)

3. **Usage**: Factorials are commonly used in combinatorial mathematics to count the number of permutations and combinations. For example, the number of permutations of ( n ) distinct objects is ( n! ). Factorials are also used in probability theory, calculus, and various other areas of mathematics.

4. **Properties**:
-( 0! = 1 ): By convention, the factorial of 0 is defined to be 1.
( n! = n \times (n-1)! ): This recursive property is often used to compute factorials.
– Factorials grow rapidly as ( n ) increases. For large values of ( n ), factorials become quite large.

Factorial is a fundamental mathematical concept with applications in various fields, and it provides a way to efficiently represent and compute the products of consecutive integers.

Scroll to Top