Write a program to find factorial of a number in java. This question is generally asked in interviews at fresher level. So first try to solve this problem on it's own.

There are two approaches to solve this problem.

i) By using iterative method.

ii) Using recursion.

Difference between iteration and recursion

Find factorial of a number using recursion in C, C++

Java programs

Factorial of a input number is : 120

There are two approaches to solve this problem.

i) By using iterative method.

ii) Using recursion.

Difference between iteration and recursion

Find factorial of a number using recursion in C, C++

Java programs

## Find Factorial of a Number in Java - Iterative Approach

package factorial; import java.util.*; public class Factorial { /** * @param args the command line arguments */ public static void main(String[] args) { int num, fact = 1; Scanner in = new Scanner(System.in); System.out.println ("Enter a number to calculate it's factorial "); /* Taking input from user */ num = in.nextInt(); /* If input number is greater than zero */ if (num >= 0) { /** * Suppose if user has input 4 * 4 * 3 * 2 * 1 */ for (int i = 1; i <= num; i++) { fact = fact * i; } System.out.println("Factorial of a input number is "+ fact); } } }

**Output :****Enter a number to calculate it's factorial : 5**

Factorial of a input number is : 120

## No comments:

## Post a Comment