We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 0e2f4ed commit e979503Copy full SHA for e979503
34.Recursion/cwh_34_recursion.java
@@ -0,0 +1,32 @@
1
+public class cwh_34_recursion {
2
+ // factorial(0) = 1
3
+ // factorial(n) = n * n-1 *....1
4
+ // factorial(5) = 5 * 4 * 3 * 2 * 1 = 120
5
+ // factorial(n) = n * factorial(n-1)
6
+
7
+ static int factorial(int n){
8
+ if(n==0 || n==1){
9
+ return 1;
10
+ }
11
+ else{
12
+ return n * factorial(n-1);
13
14
15
+ static int factorial_iterative(int n){
16
17
18
19
20
+ int product = 1;
21
+ for (int i=1;i<=n;i++){ // 1 to n
22
+ product *= i;
23
24
+ return product;
25
26
27
+ public static void main(String[] args) {
28
+ int x = 0;
29
+ System.out.println("The value of factorial x is: " + factorial(x));
30
+ System.out.println("The value of factorial x is: " + factorial_iterative(x));
31
32
+}
0 commit comments