Skip to content

Commit ff92dab

Browse files
committed
add listing tags
1 parent 3fd0c7c commit ff92dab

1 file changed

Lines changed: 9 additions & 3 deletions

File tree

source/ch7_recursion.ptx

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,8 @@
3636
<p>
3737
Here is a Python implementation of factorial using just one function:
3838
</p>
39-
<program xml:id="factorial-python-function" interactive="activecode" language="python">
39+
<listing xml:id="factorial-python-function">
40+
<program interactive="activecode" language="python">
4041
<code>
4142
def factorial(n):
4243
# Check for negative numbers
@@ -54,11 +55,13 @@ print(str(number) + "! is " + str(factorial(number)))
5455

5556
</code>
5657
</program>
58+
</listing>
5759

5860
<p>
5961
Many Python programs organize related functions into classes. The same factorial function can be placed inside a class as a method instead of as a function. When this is done, you need to create an instance of the class in order to call the method. Below, we create the class <c>MathTools</c> with a method <c>factorial</c>, and we call it from the <c>main</c> function.
6062
</p>
61-
<program xml:id="factorial-python-class" interactive="activecode" language="python">
63+
<listing xml:id="factorial-python-class">
64+
<program interactive="activecode" language="python">
6265
<code>
6366
class MTools:
6467
def factorial(self, n):
@@ -81,14 +84,16 @@ def main():
8184
main()
8285
</code>
8386
</program>
87+
</listing>
8488

8589
<p>
8690
See if you can spot the differences in the Java version below.
8791
</p>
8892
<p>
8993
Here is the equivalent Java code:
9094
</p>
91-
<program xml:id="factorial-java-class" interactive="activecode" language="java">
95+
<listing xml:id="factorial-java-class">
96+
<program interactive="activecode" language="java">
9297
<code>
9398
public class MTools {
9499
public static int factorial(int n) {
@@ -112,6 +117,7 @@ public class MTools {
112117
}
113118
</code>
114119
</program>
120+
</listing>
115121
<p>
116122
Notice the key differences from Python: instead of <c>def factorial(n):</c>, Java uses <c>public static int factorial(int n)</c> which declares the method's visibility as <c>public</c>, that it belongs to the class rather than an instance (hence, <c>static</c>), the return type as integer, and the parameter type also as integer. The recursive logic—base case and recursive step—remains identical to Python, and, of course, all code blocks use curly braces <c>{}</c> instead of indentation.
117123
</p>

0 commit comments

Comments
 (0)