|
@@ -0,0 +1,41 @@
|
|
1
|
+Jonathan Hinds
|
|
2
|
+Code Sample: RecursionExampleDirectory
|
|
3
|
+
|
|
4
|
+//pre: n >= 0
|
|
5
|
+//method fact takes in an int >= 0
|
|
6
|
+public static int fact(int n)
|
|
7
|
+{
|
|
8
|
+ //initialize the result to 0
|
|
9
|
+ int result = 0;
|
|
10
|
+ //if the number entered is 0
|
|
11
|
+ if(n == 0)
|
|
12
|
+ //set result to 1
|
|
13
|
+ result = 1;
|
|
14
|
+ //if the number entered is not 0
|
|
15
|
+ else
|
|
16
|
+ //the result is set = to the original input * the result
|
|
17
|
+ //of fact if you subtract 1 from the original input
|
|
18
|
+ result = n * fact(n-1);
|
|
19
|
+ //
|
|
20
|
+ return result;
|
|
21
|
+}
|
|
22
|
+
|
|
23
|
+the fact method takes in an integer ( n ) which must be greater than 0
|
|
24
|
+and outputs an integer ( result ) which is a product of n * (n - 1).
|
|
25
|
+This method recursively calls itself, multiplying itself by 1 less of
|
|
26
|
+what its original input was and exiting once ( n ) the input is 0, the
|
|
27
|
+code then continues in order downward to the return of the result.
|
|
28
|
+this means, 5 goes in, 5 isn't 0 so we call fact again on n-1
|
|
29
|
+this means, 4 goes in, 4 isn't 0 so we call fact again on n-1
|
|
30
|
+this means, 3 goes in, 3 isn't 0 so we call fact again on n-1
|
|
31
|
+... and so forth until 0 goes in.
|
|
32
|
+Once 0 goes in, we see that n == 0; set result to 1 and move outward returning
|
|
33
|
+the result to the previous time fact was called.
|
|
34
|
+this means when n == 0, return 1 to the previous time it was calculated.
|
|
35
|
+the previous time it was calculated ( n + 1 ) n was == 1. before that n == 2
|
|
36
|
+before that n == 3 each time multiplying itself by what it was previously.
|
|
37
|
+Recursion can be used to execute a task any number of times until a specific
|
|
38
|
+result is shown. This would be used in place of a for or while loop
|
|
39
|
+when its unknown how many times the method needs to run. In the event
|
|
40
|
+that the exit condition is never specified or never met - recursion will
|
|
41
|
+take place infinitely until a memory error occurs.
|