File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments