Skip to content

Commit bda4a54

Browse files
committed
Added Factorial Program.
1 parent 78f4bb7 commit bda4a54

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Basic-Java/Factorial.java

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import java.util.Scanner;
2+
3+
public class Factorial {
4+
5+
public static void main(String[] args) {
6+
7+
System.out.println("Program to find factorial of a number\n---");
8+
9+
int num;
10+
Scanner scanner = new Scanner (System.in);
11+
12+
System.out.print("Enter the number: ");
13+
num = scanner.nextInt();
14+
15+
if (num>20 || num< -20) {
16+
System.out.println("Cannot perform factorial for input greater than or lesser than 20.");
17+
end();
18+
}
19+
scanner.close();
20+
21+
if (num<0) {
22+
num = -num;
23+
System.out.println("-"+num+"! = -"+factorial(num));
24+
end();
25+
//For numbers lesser than zero.
26+
}
27+
else {
28+
System.out.println(num+"! = "+factorial(num));
29+
end();
30+
//For numbers greater than or equal to zero.
31+
}
32+
33+
}
34+
35+
private static long factorial(int num) {
36+
37+
long n = num, output = 1;
38+
39+
while (n>0) {
40+
output = output*n;
41+
n-=1;
42+
}
43+
return output;
44+
}
45+
46+
private static void end() {
47+
System.out.println("---\nThe Program has ended.");
48+
System.exit(0);
49+
}
50+
51+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ ___
2525
| 9 | [Prime Number Checker](/Basic-Java/PrimeNumberChecker.java) | A Program to check if the entered number is a Prime Number or not. | if/else, for loops |
2626
| 10 | [ASCII Value Of Character](/Basic-Java/AsciiOfCharacter.java) | A Program to find ASCII Value of a Character entered. | TypeCasting |
2727
| 11 | [Generate Random Number](/Basic-Java/RandomNumberGeneration.java) | A Program to generate Random Number, Also to generate Random Number between a Range. | Math.random() function |
28+
| 12 | [Factorial](/Basic-Java/Factorial.java) | A Program to find Factorial of an Integer. | while loop |
2829

2930
### List of Other Programs:
3031

0 commit comments

Comments
 (0)