# Factorial in java: Algorithm and programs

#### What is a Factorial in java?

The multiplication of all integers smaller than or equal to n is called Factorial.

For example :-

2 = 2*1 that is 2 the possibility of 2! is 2 ways  {2,1}, { 1,2 }.

3 = 3*2*1 that is 6 the possibility of 3! is 6 ways {3,2,1}, { 1,2,3 },{2,1,3},etc.

4 = 4*3*2*1 that is 24 the possibility of 4! is 24 ways {1,2,3,4}, {2,1,3,4}, {2,3,1,4},etc.

5 = 5*4*3*2*1 that is 120 the possibility of 5! is 120 ways {1,2,3,4,5},{2,1,3,5,4},{3,2,1,4,5},etc.

#### Algorithm

```START
Step 1 → Take an integer a=0,i,n=5
Step 2 → using for loop (i=1;i<=n;i++)
Step 3 → a=a*i
Step 4 → print a that is factorial
STOP```

#### The Factorial in java using a for loop

class Factorial{

public static void main(String args[]){

int i,a=1;

int n=4;

for(i=1;i<=n;i++){

a = a*i;

}

System.out.println(“Factorial of “+n+” : “+a);

}

}

#### Output

Factorial of 5: 120

#### The Factorial in java using a recursion

class Factorial{

static int fact(int n){

if (n == 0)

return 1;

else

return(n * fact(n-1));

}

public static void main(String args[]){

int i,fact=1;

int n=5;

fact = fact(n);

System.out.println(“Factorial of “+n+” : “+fact);

}

}

#### Output

Factorial of 5: 120

#### The Factorial in java using a while loop

public class Factorial {

public static void main(String[] args) {

int n = 5,i;
long fact = 1;
while(i<=n)
{
fact
= fact * i;
i
++;
}
System.out.println(“Factorial of “+n+” : “+fact);
}
}

#### Output

Factorial of 5: 120

#### The Armstrong number in java using a scanner

import java.util.Scanner;

class Factorial
{
public static void main(String args[])
{
int n, i, f = 1;

System.out.println(“Enter an number to find factorial”);
Scanner in = new Scanner(System.in);

n = in.nextInt();

if (n < 0)
System.out.println(“Number should be positive.”);
else
{
for (i = 1; i <= n; i++)
f = f*i;

System.out.println(“Factorial of “+n+” = “+f);
}
}
}

#### Click here for more questions in java

Integer Palindrome in java: Algorithm and programs

String Palindrome in java: Algorithm and programs

Fibonacci series in java: Algorithm and Programs