## Find out Factorial of a Given Number - with and with out Recursion

Here is output :

**With Out Recursion**

import java.io.*;

class FactorialWithoutRecursion

{

public static void main(String args[]) throws IOException

{

int i, product=1;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Number : ");

int n=Integer.parseInt(br.readLine());

System.out.print("Factorial of " + n + " is.. ");

for(i=n;i>=1;i--)

{

if(i!=1)

{

System.out.print(i + " * ");

}

else

{

System.out.print(i );

}

product=product*i;

}

System.out.println(" = " + product);

}

}

class FactorialWithoutRecursion

{

public static void main(String args[]) throws IOException

{

int i, product=1;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Number : ");

int n=Integer.parseInt(br.readLine());

System.out.print("Factorial of " + n + " is.. ");

for(i=n;i>=1;i--)

{

if(i!=1)

{

System.out.print(i + " * ");

}

else

{

System.out.print(i );

}

product=product*i;

}

System.out.println(" = " + product);

}

}

- Save the file with name FactorialWithoutRecursion.java
- Compile with: javac FactorialWithoutRecursion.java
- Run with: java FactorialWithoutRecursion

**With use of Recursion:**

Out Put is as following :

import java.io.*;

class Factorial

{

// this is a recursive function

int fact(int n)

{

int result;

if(n!=1)

{

System.out.print(n+" * ");

}

else

{

System.out.print( n );

}

if(n==1) return 1;

result = fact(n-1) * n;

return result;

}

}

class FactWithRecursion

{

public static void main(String args[]) throws IOException

{

int r;

Factorial f = new Factorial();

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Number : ");

int n=Integer.parseInt(br.readLine());

System.out.print("Factorial of "+ n +" is " );

r=f.fact(n);

System.out.print(" = "+r);

}

}

class Factorial

{

// this is a recursive function

int fact(int n)

{

int result;

if(n!=1)

{

System.out.print(n+" * ");

}

else

{

System.out.print( n );

}

if(n==1) return 1;

result = fact(n-1) * n;

return result;

}

}

class FactWithRecursion

{

public static void main(String args[]) throws IOException

{

int r;

Factorial f = new Factorial();

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

System.out.println("Enter the Number : ");

int n=Integer.parseInt(br.readLine());

System.out.print("Factorial of "+ n +" is " );

r=f.fact(n);

System.out.print(" = "+r);

}

}

- Save the file with name FactWithRecursion.java
- Compile with: javac FactWithRecursion.java
- Run with: java FactWithRecursion

## No comments:

## Post a Comment