-
Notifications
You must be signed in to change notification settings - Fork 368
/
factorial.java
29 lines (23 loc) · 959 Bytes
/
factorial.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/*********************************************************************
FACTORIAL PROGRAM
Factorial is represented by !. It is calculated by mutiplying natural
numbers upto that number, i.e., n! = 1 x 2 x 3... x n.
(n should be positive)
Note: 0! = 1 and 1! = 1
**********************************************************************/
import java.util.Scanner; // scanner class
public class factorial
{
static int factorialNum(int num){
if(num == 0 || num == 1) // factorial of 0 and 1 is 1
return 1;
else // if num > 1
return (num * factorialNum(num - 1));
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number:");
int num = scan.nextInt(); //factorial of this no will be calculated
System.out.println("Factorial of " + num + " is " + factorialNum(num));
}
}