Skip to main content
Logo image

Section 23 Program Listings (with code in the title)

View Source for section
<section xml:id="section-programs" label="section-programs">
    <title>Program Listings (with <c>code</c> in the title)</title>
    <p>
      Sage cells can be used for Python examples,
      but Sage uses a mild amount of pre-parsing,
      so that might not be a wise decision,
      especially in instructional settings.
      We might implement Skulpt or Brython (in-browser Python) or the Python language argument to the Sage Cell Server.
      To see examples of authoring Sage cells,
      have a look at Section<nbsp /><xref ref="section-sage-cells" />.
    </p>
    <p>
      In the meantime, program listings,
          <idx><h>listing</h></idx>
          <idx><h>program listing</h></idx>
      especially with syntax highlighting, is useful all by itself.
      The
      <q>R</q>
      language might not be a bad stand-in for pseudo-code,
      as it supports assignment with a left arrow and has fairly generic procedural syntax for control structures and data structures.
      Or maybe Pascal would be a good choice?
      Here is an example of R. Note in the source that the entire block of code is wrapped in a CDATA section due to the four left angle brackets.
      We do not recommend this technique for isolated problem characters,
      but it is a life-saver for situations like the <init>XSLT</init> code just following.
    </p>



<program language="r">
<code>
n_loops &lt;- 10
x.means &lt;- numeric(n_loops)  # create a vector of zeros for results
for (i in 1:n_loops){
x &lt;- as.integer(runif(100, 1, 7))  # 1 to 6, uniformly
x.means[i] &lt;- mean(x)
}
x.means
</code>
</program>
    <p>
      And some self-referential XSL:
    </p>

<program language="xslt" margins="15%">
&lt;xsl:template match="biblio" mode="number"&gt;
&lt;xsl:apply-templates select="." mode="structural-number"/&gt;
&lt;xsl:text&gt;.&lt;/xsl:text&gt;
&lt;xsl:number from="references" level="any" count="biblio"/&gt;
&lt;/xsl:template&gt;
</program>
    <p>
      Matlab is a commercial language for mathematics,
      while Octave in an open source version.
      The <attr>language</attr> values of <c>matlab</c> and <c>octave</c> are somewhat interchangeable.
      Following is a very slighlty edited version of an example from
      <url href="http://www.public.asu.edu/~hhuang38/hph_matlab_basic2013_1.pdf" visual="www.public.asu.edu/~hhuang38/hph_matlab_basic2013_1.pdf"><articletitle>50 Basic Examples for Matlab</articletitle></url>.
    </p>

<program language="matlab">
<code>
a = [0:0.5:5]; % A Matlab comment here
b = 2*a.^2 + 3*a -5;
c = 1.2*a.^2+4*a-3;
subplot(1,2,1)
plot(a,b,'-or','MarkerFaceColor','g','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve ','Location','NorthWest')
subplot(1,2,2)
plot(a,c,'--ok','MarkerFaceColor','c','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve 2','Location','NorthWest')
</code>
</program>
    <p>
      You can write made-up pseudo-code,
      but you might explain to a reader what your symbols all mean.
      This routine takes the <m>m\times n</m> marix <m>A</m> to reduced row-echelon form.
      Note that with no language specified,
      there is no special formatting or use of color.
      Note in the source the use of escaped characters for the three less-than symbols.
    </p>
<program margins="5%">
<code>
input m, n and A
r := 0
for j := 1 to n
i := r+1
while i &lt;= m and A[i,j] == 0
i := i+1
if i &lt; m+1
r := r+1
swap rows i and r of A (row op 1)
scale A[r,j] to a leading 1 (row op 2)
for k := 1 to m, k &lt;&gt; r
make A[k,j] zero (row op 3, employing row r)
output r and A
</code>
</program>
    <p>
      Look in the <c>pretext-common.xsl</c> file to see the strings to use to identify languages.
      Always all-lowercase, no symbols, no punctuation.
    </p>
    <p>
      Note that the above examples all have slightly different widths
      (theser are very evident in print with the frames).
      As 2-D atomic objects,
      to place them in the narrative requires the layout features of a <c>sidebyside</c> element.
      Then <c>width</c> and/or <c>margin</c> attributes will influence the width of the panel.
    </p>
    <p>
      A <c>program</c> may also be nested inside a <c>listing</c>,
      which behaves similar to a <c>figure</c>.
      You can provide a <c>caption</c>,
      and the listing will be numbered along with tables and figures.
      This then makes it possible to cross-reference the listing,
      such as <xref ref="listing-c-hello" text="type-global" />.
      It also removes the requirement of wrapping the <c>program</c> in a <c>sidebyside</c>.
      For technical reasons,
      the three examples above will not split across a page break in PDF output,
      but the placement inside a <c>listing</c> will allow splits,
      as you should see in at least one example following.
    </p>
<listing xml:id="listing-c-hello">
<caption>C Version of <q>Hello, World!</q></caption>
<program language="c">
<code>
/* Hello World program */
#include&lt;stdio.h&gt;
main()
{
printf("Hello, World!");
}
</code>
</program>
</listing>
    <p>
      A <tag>program</tag> may include line numbers.
    </p>
<listing xml:id="program-line-numbers">
<caption>A static Java program with line numbers</caption>
<program interactive="no" language="java" line-numbers="yes">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
</listing>
    <p>
      A <tag>program</tag> may also include highlighted lines.
    </p>
<listing xml:id="program-highlight-lines">
<caption>A static Java program with line numbers</caption>
<program interactive="no" language="java" line-numbers="yes" highlight-lines="1,3-5">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
</listing>
    <p>
      If you are discussing algorithms in the abstract
      (or even concretely),
      you can set them off like a theorem,
      with a number, a title and a target for cross-references.
      Sometimes you claim an algorithm produces something in particular,
      or has certain properties,
      such as a theoretical run time,
      so a proof may be included.
      See the discussion just preceding about (limited) options for pseudo-code.
    </p>
    <algorithm xml:id="algorithm-sieve-eratosthenes">
      <title>Sieve of Eratosthenes</title>
      <statement>
        <p>
          On input of a positive integer <c>n</c> this algorithm will compute all the prime numbers up to,
          and including, <c>n</c>.
          It was named for Eratosthenes of Cyrene (<ca /> 276 BC<ndash /><ca /> 195/194 BC) by Nicomachus (<ca /> 60<ndash /><ca /> 120 CE) in
          <pubtitle>Introduction to Arithmetic</pubtitle>.
          (
          <url href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" visual="en.wikipedia.org/wiki/Sieve_of_Eratosthenes">Wikipedia</url>,
          2015)
          <ol>
            <li>Input: <c>n</c></li>
            <li>
              Form the list of all integers from <c>2</c> to <c>n</c>
            </li>
            <li>Set <c>p = 2</c></li>
            <li>
              <p>
                While <c>p &lt; sqrt(n)</c>
                <ol marker="1.">
                  <li>
                    If present, remove from the list multiples <c>2p, 3p, ...</c>
                  </li>
                  <li>
                    If <c>p</c> is now the last element of the list, stop
                  </li>
                  <li>
                    Otherwise, set <c>p</c> to the element of the list immediately after current <c>p</c>
                  </li>
                </ol>
              </p>
            </li>
            <li>Output: the remaining elements of the list</li>
          </ol>
        </p>
      </statement>
      <proof>
        <p>
          Any element removed is a non-trivial product of two integers and hence composite.
          So no prime is is ever removed from the list.
        </p>
        <p>
          Each composite number is a multiple of some prime,
          and since no prime is ever removed,
          each composite will be removed.
          Hence the removed elements are precisely the set of composite numbers in the list and thus the remainder are precisely the primes on the list.
        </p>
      </proof>
    </algorithm>
    <p>
      If you are writing about system-level software,
      you may need to write numbers in hexadecimal or binary.
      Here we use a numbered,
      displayed equation (mathematics) and <latex /> macros such as <c>\texttt</c> for a monospace text font,
      and <c>\;</c> for spacing/grouping the bits of the binary number.
      <men>
        \texttt{6C2A}_{16} = \texttt{0110}\;\texttt{1100}\;\texttt{0010}\;\texttt{1010}_{2}
      </men>
      If you use these constructions repeatedly,
      then some <latex /> macros might be useful.
      It might also be beneficial for us to add some <pretext /> markup for such numbers used in a paragraph<mdash />send us a feature request.
    </p>
    <theorem xml:id="theorem-detached">
      <statement>
        <p>
          This is a spurious theorem to break up the run of consecutive <c>listing</c> so we might test the effect.
        </p>
      </statement>
    </theorem>
    <p>
      And this is a spurious paragraph to prove that the theorem beforehand,
      and the proof following, are distinct from one another.
    </p>
    <proof ref="theorem-detached" text="type-global">
      <p>
        This is a proof that is authored
        <q>detached.</q>
        It is not associated with the theorem above in a way other than simply following it.
      </p>
    </proof>
    <p>
      A specialized version of a program listing is an interactive command/response session at a command-line,
      where differing fonts are used to differentiate the system prompt,
      the user's commands, and the system's reaction.
      A <c>console</c> session may be used by itself inside a <c>sidebyside</c>,
      or it can be wrapped in a listing to get a number and a caption.
      As elsewhere,
      you will need to escape ampersands and angle brackets
      (such as if you have a command using redirection),
      using <c>&amp;amp;</c>,
      <c>&amp;lt;</c>,
      and <c>&amp;gt;</c> in your source.
    </p>
<listing xml:id="console-raspberry-pi">
<caption>Console Session: <c>int</c> and <c>float</c></caption>
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>gcc -Wall -o intAndFloat intAndFloat.c</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
</listing>
    <p>
      Here is the plain version, some layout control.
      We simply place a small margin on the left
      (at 4% width).
    </p>
    <console prompt="pi@raspberrypi ~/progs/chap02 $ " margins="4%">
<input>gcc -Wall -o intAndFloat intAndFloat.c</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
      <input />
    </console>
    <p>
      If your console input exceeds more than one line,
      you can author it across several lines and your choice of line breaks will be reflected in the rendering.
      You can decide to indent lines after the first one for clarity,
      if desired.
      You can also decide if your audience needs line-continuation characters or not.
    </p>
<listing xml:id="console-raspberry-pi-multi">
<caption>Console Session: <c>int</c> and <c>float</c> (multi-line input)</caption>
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>
gcc -Wall
-o intAndFloat intAndFloat.c
</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
</listing>
    <p>
      Notice in the HTML version of the above example that when you highlight all,
      or a portion,
      of the listing for a cut-and-paste that the prompts are not included.
    </p>
    <p>
      The next listing is just absurdity,
      to check various characters from <latex /> that are otherwise employed by the code supporting consoles,
      and some Latin-1 characters.
      We test each in a prompt, input, and output.
      We use <c>(*</c> and <c>*)</c> as sequences used to escape embedded <latex /> commands,
      so we test those also.
    </p>
<listing>
<caption>Console Session: problematic <latex /> characters</caption>
<console>
<input prompt="A backslash \ here  ">A backslash \ here</input>
<output>A backslash \ here</output>
<input prompt="A begin group { here  ">A begin group { here</input>
<output>A begin group { here</output>
<input prompt="An end group { here  ">An end group } here</input>
<output>An end group } here</output>
<input prompt="An open escape sequence (* here  ">An open escape sequence (* here</input>
<output>An open escape sequence (* here</output>
<input prompt="An end escape sequence *) here  ">An end escape sequence *) here</input>
<output>An end escape sequence *) here</output>
<input prompt="Some quotation marks ` ' " here  ">Some quotation marks ` ' " here</input>
<output>Some quotation marks ` ' " here</output>
<input prompt="The rest &amp; % $ # _ ~ ^ of LaTeX  ">The rest &amp; % $ # _ ~ ^ of LaTeX</input>
<output>The rest &amp; % $ # _ ~ ^ of LaTeX</output>
<input prompt="Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß  ">Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</input>
<output>Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</output>
</console>
</listing>
    <p>
      We conclude this section with a longer example of a program listing,
      an assembly language program from Bob Plantz,
      included to test a <c>listing</c> breaking across pages in PDF output.
    </p>
<listing>
<caption>A longer program listing</caption>
<program>
<code>
@ structPass2.s
@ Allocates two structs and assigns a value to each field
@ in each struct, then displays the values.
@ Bob Plantz - 6 July 2016
@ Constants for assembler
.include "theTag_struct.s"  @ theTag struct defs.
.equ    y,-28           @ y struct
.equ    x,-16           @ x struct
.equ    locals,28       @ space for the structs
@ Constant program data
.section .rodata
.align  2
displayX:
.asciz        "x fields:\n"
displayY:
.asciz        "y fields:\n"
dispAChar:
.asciz        "         aChar = "
dispAnInt:
.asciz        "         anInt = "
dispOtherChar:
.asciz        "   anotherChar = "
@ The program
.text
.align  2
.global main
.type   main, %function
main:
stmfd   sp!, {r4, fp, lr}   @ save caller's info
add     fp, sp, #8      @ our frame pointer
sub     sp, sp, #locals @ for the structs
@ fill the x struct
add     r0, fp, #x      @ address of x struct
mov     r1, #'1
mov     r2, #456
mov     r3, #'2
bl      loadStruct
@ fill the y struct
add     r0, fp, #y      @ address of y struct
mov     r1, #'a
mov     r2, #123
mov     r3, #'b
bl      loadStruct
@ display x struct
add     r4, fp, #x        @ address of x struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
@ display y struct
add     r4, fp, #y        @ address of y struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
mov     r0, #0          @ return 0;
sub     sp, fp, #8      @ restore sp
ldmfd   sp!, {r4, fp, pc}   @ restore and return
.align  2
@ addresses of messages
displayXaddr:
.word   displayX
displayYaddr:
.word   displayY
dispACharAddr:
.word   dispAChar
dispAnIntAddr:
.word   dispAnInt
dispOtherCharAddr:
.word   dispOtherChar
</code>
</program>
</listing>
  </section>
Sage cells can be used for Python examples, but Sage uses a mild amount of pre-parsing, so that might not be a wise decision, especially in instructional settings. We might implement Skulpt or Brython (in-browser Python) or the Python language argument to the Sage Cell Server. To see examples of authoring Sage cells, have a look at Section 3.
In the meantime, program listings, especially with syntax highlighting, is useful all by itself. The “R” language might not be a bad stand-in for pseudo-code, as it supports assignment with a left arrow and has fairly generic procedural syntax for control structures and data structures. Or maybe Pascal would be a good choice? Here is an example of R. Note in the source that the entire block of code is wrapped in a CDATA section due to the four left angle brackets. We do not recommend this technique for isolated problem characters, but it is a life-saver for situations like the XSLT code just following.
View Source for program
<program language="r">
<code>
n_loops &lt;- 10
x.means &lt;- numeric(n_loops)  # create a vector of zeros for results
for (i in 1:n_loops){
x &lt;- as.integer(runif(100, 1, 7))  # 1 to 6, uniformly
x.means[i] &lt;- mean(x)
}
x.means
</code>
</program>
n_loops <- 10
x.means <- numeric(n_loops)  # create a vector of zeros for results
for (i in 1:n_loops){
x <- as.integer(runif(100, 1, 7))  # 1 to 6, uniformly
x.means[i] <- mean(x)
}
x.means
And some self-referential XSL:
View Source for program
<program language="xslt" margins="15%">
&lt;xsl:template match="biblio" mode="number"&gt;
&lt;xsl:apply-templates select="." mode="structural-number"/&gt;
&lt;xsl:text&gt;.&lt;/xsl:text&gt;
&lt;xsl:number from="references" level="any" count="biblio"/&gt;
&lt;/xsl:template&gt;
</program>
<xsl:template match="biblio" mode="number">
<xsl:apply-templates select="." mode="structural-number"/>
<xsl:text>.</xsl:text>
<xsl:number from="references" level="any" count="biblio"/>
</xsl:template>
Matlab is a commercial language for mathematics, while Octave in an open source version. The @language values of matlab and octave are somewhat interchangeable. Following is a very slighlty edited version of an example from “50 Basic Examples for Matlab”
 1 
www.public.asu.edu/~hhuang38/hph_matlab_basic2013_1.pdf
.
View Source for program
<program language="matlab">
<code>
a = [0:0.5:5]; % A Matlab comment here
b = 2*a.^2 + 3*a -5;
c = 1.2*a.^2+4*a-3;
subplot(1,2,1)
plot(a,b,'-or','MarkerFaceColor','g','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve ','Location','NorthWest')
subplot(1,2,2)
plot(a,c,'--ok','MarkerFaceColor','c','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve 2','Location','NorthWest')
</code>
</program>
a = [0:0.5:5]; % A Matlab comment here
b = 2*a.^2 + 3*a -5;
c = 1.2*a.^2+4*a-3;
subplot(1,2,1)
plot(a,b,'-or','MarkerFaceColor','g','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve ','Location','NorthWest')
subplot(1,2,2)
plot(a,c,'--ok','MarkerFaceColor','c','LineWidth',2)
xlabel('X'); ylabel('Y'); legend('Curve 2','Location','NorthWest')
You can write made-up pseudo-code, but you might explain to a reader what your symbols all mean. This routine takes the \(m\times n\) marix \(A\) to reduced row-echelon form. Note that with no language specified, there is no special formatting or use of color. Note in the source the use of escaped characters for the three less-than symbols.
View Source for program
<program margins="5%">
<code>
input m, n and A
r := 0
for j := 1 to n
i := r+1
while i &lt;= m and A[i,j] == 0
i := i+1
if i &lt; m+1
r := r+1
swap rows i and r of A (row op 1)
scale A[r,j] to a leading 1 (row op 2)
for k := 1 to m, k &lt;&gt; r
make A[k,j] zero (row op 3, employing row r)
output r and A
</code>
</program>
input m, n and A
r := 0
for j := 1 to n
i := r+1
while i <= m and A[i,j] == 0
i := i+1
if i < m+1
r := r+1
swap rows i and r of A (row op 1)
scale A[r,j] to a leading 1 (row op 2)
for k := 1 to m, k <> r
make A[k,j] zero (row op 3, employing row r)
output r and A
Look in the pretext-common.xsl file to see the strings to use to identify languages. Always all-lowercase, no symbols, no punctuation.
Note that the above examples all have slightly different widths (theser are very evident in print with the frames). As 2-D atomic objects, to place them in the narrative requires the layout features of a sidebyside element. Then width and/or margin attributes will influence the width of the panel.
A program may also be nested inside a listing, which behaves similar to a figure. You can provide a caption, and the listing will be numbered along with tables and figures. This then makes it possible to cross-reference the listing, such as Listing 23.1. It also removes the requirement of wrapping the program in a sidebyside. For technical reasons, the three examples above will not split across a page break in PDF output, but the placement inside a listing will allow splits, as you should see in at least one example following.
View Source for listing
<listing xml:id="listing-c-hello">
<caption>C Version of <q>Hello, World!</q></caption>
<program language="c">
<code>
/* Hello World program */
#include&lt;stdio.h&gt;
main()
{
printf("Hello, World!");
}
</code>
</program>
</listing>
View Source for program
<program language="c">
<code>
/* Hello World program */
#include&lt;stdio.h&gt;
main()
{
printf("Hello, World!");
}
</code>
</program>
/* Hello World program */
#include<stdio.h>
main()
{
printf("Hello, World!");
}
Listing 23.1. C Version of “Hello, World!”
A <program> may include line numbers.
View Source for listing
<listing xml:id="program-line-numbers">
<caption>A static Java program with line numbers</caption>
<program interactive="no" language="java" line-numbers="yes">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
</listing>
View Source for program
<program interactive="no" language="java" line-numbers="yes">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
Listing 23.2. A static Java program with line numbers
A <program> may also include highlighted lines.
View Source for listing
<listing xml:id="program-highlight-lines">
<caption>A static Java program with line numbers</caption>
<program interactive="no" language="java" line-numbers="yes" highlight-lines="1,3-5">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
</listing>
View Source for program
<program interactive="no" language="java" line-numbers="yes" highlight-lines="1,3-5">
<code>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
</code>
</program>
import javax.swing.JFrame;  //Importing class JFrame
import javax.swing.JLabel;  //Importing class JLabel
public class HelloWorld {
public static void main(String[] args) {
JFrame frame = new JFrame();           //Creating frame
frame.setTitle("Hi!");                 //Setting title frame
frame.add(new JLabel("Hello, world!"));//Adding text to frame
frame.pack();                          //Setting size to smallest
frame.setLocationRelativeTo(null);     //Centering frame
frame.setVisible(true);                //Showing frame
}
}
Listing 23.3. A static Java program with line numbers
If you are discussing algorithms in the abstract (or even concretely), you can set them off like a theorem, with a number, a title and a target for cross-references. Sometimes you claim an algorithm produces something in particular, or has certain properties, such as a theoretical run time, so a proof may be included. See the discussion just preceding about (limited) options for pseudo-code.

Proof.

View Source for proof
<proof>
  <p>
    Any element removed is a non-trivial product of two integers and hence composite.
    So no prime is is ever removed from the list.
  </p>
  <p>
    Each composite number is a multiple of some prime,
    and since no prime is ever removed,
    each composite will be removed.
    Hence the removed elements are precisely the set of composite numbers in the list and thus the remainder are precisely the primes on the list.
  </p>
</proof>
Any element removed is a non-trivial product of two integers and hence composite. So no prime is is ever removed from the list.
Each composite number is a multiple of some prime, and since no prime is ever removed, each composite will be removed. Hence the removed elements are precisely the set of composite numbers in the list and thus the remainder are precisely the primes on the list.
If you are writing about system-level software, you may need to write numbers in hexadecimal or binary. Here we use a numbered, displayed equation (mathematics) and macros such as \texttt for a monospace text font, and \; for spacing/grouping the bits of the binary number.
\begin{equation} \texttt{6C2A}_{16} = \texttt{0110}\;\texttt{1100}\;\texttt{0010}\;\texttt{1010}_{2}\tag{23.1} \end{equation}
If you use these constructions repeatedly, then some macros might be useful. It might also be beneficial for us to add some PreTeXt markup for such numbers used in a paragraph—send us a feature request.
And this is a spurious paragraph to prove that the theorem beforehand, and the proof following, are distinct from one another.

Proof. (Theorem 23.5)

View Source for proof
<proof ref="theorem-detached" text="type-global">
  <p>
    This is a proof that is authored
    <q>detached.</q>
    It is not associated with the theorem above in a way other than simply following it.
  </p>
</proof>
Theorem 23.5
This is a proof that is authored “detached.” It is not associated with the theorem above in a way other than simply following it.
A specialized version of a program listing is an interactive command/response session at a command-line, where differing fonts are used to differentiate the system prompt, the user’s commands, and the system’s reaction. A console session may be used by itself inside a sidebyside, or it can be wrapped in a listing to get a number and a caption. As elsewhere, you will need to escape ampersands and angle brackets (such as if you have a command using redirection), using &amp;, &lt;, and &gt; in your source.
View Source for listing
<listing xml:id="console-raspberry-pi">
<caption>Console Session: <c>int</c> and <c>float</c></caption>
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>gcc -Wall -o intAndFloat intAndFloat.c</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
</listing>
View Source for console
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>gcc -Wall -o intAndFloat intAndFloat.c</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
pi@raspberrypi ~/progs/chap02 $ gcc -Wall -o intAndFloat intAndFloat.c
pi@raspberrypi ~/progs/chap02 $ ./intAndFloat
The integer is 19088743 and the float is 19088.742188
pi@raspberrypi ~/progs/chap02 $ 
Listing 23.6. Console Session: int and float
Here is the plain version, some layout control. We simply place a small margin on the left (at 4% width).
View Source for console
<console prompt="pi@raspberrypi ~/progs/chap02 $ " margins="4%">
<input>gcc -Wall -o intAndFloat intAndFloat.c</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
      <input />
    </console>
pi@raspberrypi ~/progs/chap02 $ gcc -Wall -o intAndFloat intAndFloat.c
pi@raspberrypi ~/progs/chap02 $ ./intAndFloat
The integer is 19088743 and the float is 19088.742188
pi@raspberrypi ~/progs/chap02 $ 
If your console input exceeds more than one line, you can author it across several lines and your choice of line breaks will be reflected in the rendering. You can decide to indent lines after the first one for clarity, if desired. You can also decide if your audience needs line-continuation characters or not.
View Source for listing
<listing xml:id="console-raspberry-pi-multi">
<caption>Console Session: <c>int</c> and <c>float</c> (multi-line input)</caption>
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>
gcc -Wall
-o intAndFloat intAndFloat.c
</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
</listing>
View Source for console
<console prompt="pi@raspberrypi ~/progs/chap02 $ ">
<input>
gcc -Wall
-o intAndFloat intAndFloat.c
</input>
<input>./intAndFloat</input>
<output>
The integer is 19088743 and the float is 19088.742188
</output>
<input />
</console>
pi@raspberrypi ~/progs/chap02 $ gcc -Wall
-o intAndFloat intAndFloat.c
pi@raspberrypi ~/progs/chap02 $ ./intAndFloat
The integer is 19088743 and the float is 19088.742188
pi@raspberrypi ~/progs/chap02 $ 
Listing 23.7. Console Session: int and float (multi-line input)
Notice in the HTML version of the above example that when you highlight all, or a portion, of the listing for a cut-and-paste that the prompts are not included.
The next listing is just absurdity, to check various characters from that are otherwise employed by the code supporting consoles, and some Latin-1 characters. We test each in a prompt, input, and output. We use (* and *) as sequences used to escape embedded commands, so we test those also.
View Source for listing
<listing>
<caption>Console Session: problematic <latex /> characters</caption>
<console>
<input prompt="A backslash \ here  ">A backslash \ here</input>
<output>A backslash \ here</output>
<input prompt="A begin group { here  ">A begin group { here</input>
<output>A begin group { here</output>
<input prompt="An end group { here  ">An end group } here</input>
<output>An end group } here</output>
<input prompt="An open escape sequence (* here  ">An open escape sequence (* here</input>
<output>An open escape sequence (* here</output>
<input prompt="An end escape sequence *) here  ">An end escape sequence *) here</input>
<output>An end escape sequence *) here</output>
<input prompt="Some quotation marks ` ' " here  ">Some quotation marks ` ' " here</input>
<output>Some quotation marks ` ' " here</output>
<input prompt="The rest &amp; % $ # _ ~ ^ of LaTeX  ">The rest &amp; % $ # _ ~ ^ of LaTeX</input>
<output>The rest &amp; % $ # _ ~ ^ of LaTeX</output>
<input prompt="Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß  ">Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</input>
<output>Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</output>
</console>
</listing>
View Source for console
<console>
<input prompt="A backslash \ here  ">A backslash \ here</input>
<output>A backslash \ here</output>
<input prompt="A begin group { here  ">A begin group { here</input>
<output>A begin group { here</output>
<input prompt="An end group { here  ">An end group } here</input>
<output>An end group } here</output>
<input prompt="An open escape sequence (* here  ">An open escape sequence (* here</input>
<output>An open escape sequence (* here</output>
<input prompt="An end escape sequence *) here  ">An end escape sequence *) here</input>
<output>An end escape sequence *) here</output>
<input prompt="Some quotation marks ` ' " here  ">Some quotation marks ` ' " here</input>
<output>Some quotation marks ` ' " here</output>
<input prompt="The rest &amp; % $ # _ ~ ^ of LaTeX  ">The rest &amp; % $ # _ ~ ^ of LaTeX</input>
<output>The rest &amp; % $ # _ ~ ^ of LaTeX</output>
<input prompt="Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß  ">Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</input>
<output>Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß</output>
</console>
A backslash \ here  A backslash \ here
A backslash \ here
A begin group { here  A begin group { here
A begin group { here
An end group { here  An end group } here
An end group } here
An open escape sequence (* here  An open escape sequence (* here
An open escape sequence (* here
An end escape sequence *) here  An end escape sequence *) here
An end escape sequence *) here
Some quotation marks ` ' " here  Some quotation marks ` ' " here
Some quotation marks ` ' " here
The rest & % $ # _ ~ ^ of LaTeX  The rest & % $ # _ ~ ^ of LaTeX
The rest & % $ # _ ~ ^ of LaTeX
Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß  Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß
Latin-1: ÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß
Listing 23.8. Console Session: problematic characters
We conclude this section with a longer example of a program listing, an assembly language program from Bob Plantz, included to test a listing breaking across pages in PDF output.
View Source for listing
<listing>
<caption>A longer program listing</caption>
<program>
<code>
@ structPass2.s
@ Allocates two structs and assigns a value to each field
@ in each struct, then displays the values.
@ Bob Plantz - 6 July 2016
@ Constants for assembler
.include "theTag_struct.s"  @ theTag struct defs.
.equ    y,-28           @ y struct
.equ    x,-16           @ x struct
.equ    locals,28       @ space for the structs
@ Constant program data
.section .rodata
.align  2
displayX:
.asciz        "x fields:\n"
displayY:
.asciz        "y fields:\n"
dispAChar:
.asciz        "         aChar = "
dispAnInt:
.asciz        "         anInt = "
dispOtherChar:
.asciz        "   anotherChar = "
@ The program
.text
.align  2
.global main
.type   main, %function
main:
stmfd   sp!, {r4, fp, lr}   @ save caller's info
add     fp, sp, #8      @ our frame pointer
sub     sp, sp, #locals @ for the structs
@ fill the x struct
add     r0, fp, #x      @ address of x struct
mov     r1, #'1
mov     r2, #456
mov     r3, #'2
bl      loadStruct
@ fill the y struct
add     r0, fp, #y      @ address of y struct
mov     r1, #'a
mov     r2, #123
mov     r3, #'b
bl      loadStruct
@ display x struct
add     r4, fp, #x        @ address of x struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
@ display y struct
add     r4, fp, #y        @ address of y struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
mov     r0, #0          @ return 0;
sub     sp, fp, #8      @ restore sp
ldmfd   sp!, {r4, fp, pc}   @ restore and return
.align  2
@ addresses of messages
displayXaddr:
.word   displayX
displayYaddr:
.word   displayY
dispACharAddr:
.word   dispAChar
dispAnIntAddr:
.word   dispAnInt
dispOtherCharAddr:
.word   dispOtherChar
</code>
</program>
</listing>
View Source for program
<program>
<code>
@ structPass2.s
@ Allocates two structs and assigns a value to each field
@ in each struct, then displays the values.
@ Bob Plantz - 6 July 2016
@ Constants for assembler
.include "theTag_struct.s"  @ theTag struct defs.
.equ    y,-28           @ y struct
.equ    x,-16           @ x struct
.equ    locals,28       @ space for the structs
@ Constant program data
.section .rodata
.align  2
displayX:
.asciz        "x fields:\n"
displayY:
.asciz        "y fields:\n"
dispAChar:
.asciz        "         aChar = "
dispAnInt:
.asciz        "         anInt = "
dispOtherChar:
.asciz        "   anotherChar = "
@ The program
.text
.align  2
.global main
.type   main, %function
main:
stmfd   sp!, {r4, fp, lr}   @ save caller's info
add     fp, sp, #8      @ our frame pointer
sub     sp, sp, #locals @ for the structs
@ fill the x struct
add     r0, fp, #x      @ address of x struct
mov     r1, #'1
mov     r2, #456
mov     r3, #'2
bl      loadStruct
@ fill the y struct
add     r0, fp, #y      @ address of y struct
mov     r1, #'a
mov     r2, #123
mov     r3, #'b
bl      loadStruct
@ display x struct
add     r4, fp, #x        @ address of x struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
@ display y struct
add     r4, fp, #y        @ address of y struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
mov     r0, #0          @ return 0;
sub     sp, fp, #8      @ restore sp
ldmfd   sp!, {r4, fp, pc}   @ restore and return
.align  2
@ addresses of messages
displayXaddr:
.word   displayX
displayYaddr:
.word   displayY
dispACharAddr:
.word   dispAChar
dispAnIntAddr:
.word   dispAnInt
dispOtherCharAddr:
.word   dispOtherChar
</code>
</program>
@ structPass2.s
@ Allocates two structs and assigns a value to each field
@ in each struct, then displays the values.
@ Bob Plantz - 6 July 2016
@ Constants for assembler
.include "theTag_struct.s"  @ theTag struct defs.
.equ    y,-28           @ y struct
.equ    x,-16           @ x struct
.equ    locals,28       @ space for the structs
@ Constant program data
.section .rodata
.align  2
displayX:
.asciz        "x fields:\n"
displayY:
.asciz        "y fields:\n"
dispAChar:
.asciz        "         aChar = "
dispAnInt:
.asciz        "         anInt = "
dispOtherChar:
.asciz        "   anotherChar = "
@ The program
.text
.align  2
.global main
.type   main, %function
main:
stmfd   sp!, {r4, fp, lr}   @ save caller's info
add     fp, sp, #8      @ our frame pointer
sub     sp, sp, #locals @ for the structs
@ fill the x struct
add     r0, fp, #x      @ address of x struct
mov     r1, #'1
mov     r2, #456
mov     r3, #'2
bl      loadStruct
@ fill the y struct
add     r0, fp, #y      @ address of y struct
mov     r1, #'a
mov     r2, #123
mov     r3, #'b
bl      loadStruct
@ display x struct
add     r4, fp, #x        @ address of x struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
@ display y struct
add     r4, fp, #y        @ address of y struct
ldr     r0, displayXaddr
bl      writeStr
ldr     r0, dispACharAddr @ display aChar
bl      writeStr
ldrb    r0, [r4, #aChar]
bl      putChar
bl      newLine
ldr     r0, dispAnIntAddr @ display anInt
bl      writeStr
ldr     r0, [r4, #anInt]
bl      putDecInt
bl      newLine
ldr     r0, dispOtherCharAddr @ display anotherChar
bl      writeStr
ldrb    r0, [r4, #anotherChar]
bl      putChar
bl      newLine
mov     r0, #0          @ return 0;
sub     sp, fp, #8      @ restore sp
ldmfd   sp!, {r4, fp, pc}   @ restore and return
.align  2
@ addresses of messages
displayXaddr:
.word   displayX
displayYaddr:
.word   displayY
dispACharAddr:
.word   dispAChar
dispAnIntAddr:
.word   dispAnInt
dispOtherCharAddr:
.word   dispOtherChar
Listing 23.9. A longer program listing