Skip to content

Commit e979503

Browse files
Recursion
1 parent 0e2f4ed commit e979503

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

34.Recursion/cwh_34_recursion.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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+
if(n==0 || n==1){
17+
return 1;
18+
}
19+
else{
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

Comments
 (0)